Skip to content

Instantly share code, notes, and snippets.

@tomlea
Forked from matthewrudy/bumblebee.rb
Created January 29, 2009 11:17
Show Gist options
  • Save tomlea/54506 to your computer and use it in GitHub Desktop.
Save tomlea/54506 to your computer and use it in GitHub Desktop.
<<-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
class Object
def bumblebee(*flowers)
while flowers.any?
flower = self.send(flowers.shift)
return flower unless flower.blank?
end
end
end
# 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