Skip to content

Instantly share code, notes, and snippets.

@matthewrudy
Created January 29, 2009 11:02
Show Gist options
  • Save matthewrudy/54501 to your computer and use it in GitHub Desktop.
Save matthewrudy/54501 to your computer and use it in GitHub Desktop.
The Bumblebee
<<-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) || "*unknown*"
# 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
else
return "*unknown*"
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)
=> "magicmail"
>> u.bumblebee(:something_blank) # it also works like "try" but for :blank? rather than :nil?
=> nil
>> u.bumblebee(:something_blank) || "a default" # and gets us proper ruby defaults
=> "a default"
# BOOM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment