-
-
Save tomlea/54506 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<<-BUMBLEBEE | |
The bumblebee hovers around an object, | |
looking for a flower with some pollen. | |
It goes from flower to flower, | |
trying each method in order, | |
and when it finds one that isn't empty, | |
it returns it to the hive. | |
BUMBLEBEE | |
user.bumblebee(:full_name, :first_name, :login, :email) | |
# which is equivalent to; | |
if user.full_name.present? | |
return user.full_name | |
elsif user.first_name.present? | |
return user.first_name | |
elsif user.login.present? | |
return user.login | |
elsif user.email.present? | |
return user.email | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Object | |
def bumblebee(*flowers) | |
while flowers.any? | |
flower = self.send(flowers.shift) | |
return flower unless flower.blank? | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A real world example | |
>> u = User.new | |
=> #<User id=nil email: "" firstname:""> | |
>> u.email | |
=> "" | |
>> u.firstname | |
=> "" | |
>> u.bumblebee(:email, :firstname) | |
=> nil | |
>> u.firstname = "burger" | |
=> "burger" | |
>> u.bumblebee(:email, :firstname) | |
=> "burger" | |
>> u.email = "magicmail" | |
=> "magicmail" | |
>> u.bumblebee(:email, :firstname) | |
=> "burger" | |
# BOOM |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment