3 ms·
In Ruby I defined these on Object. A little ugly if you are doing a long chain, but works fine in many cases. def if_present? # example: User.find_all_by
by xenophanes 16y ago
In Ruby I defined these on Object. A little ugly if you are doing a long chain, but works fine in many cases.
def if_present?
# example: User.find_all_by_something.if_present? || User.find_all_by_something_else
self if present?
end
def send_if_respond_to(method, *args)
# example: string_or_nil.send_if_respond_to(:strip)
send(method, *args) if respond_to?(method)
end
- jey 16y agohttp://andand.rubyforge.org/ http://andand.rubyforge.org/
- qwzybug 16y agoI like monkey patching NilClass to STFU. Bonus: the code fits in a tweet! http://mobile.twitter.com/qwzybug/status/9033799293 http://mobile.twitter.com/qwzybug/status/9033799293 Message-eating nils are one of my favorite features of Objective-C.
- ROFISH 16y agoRuby also has inline rescue as well. (Banana.find(id).plantation.state rescue nil) Chain it if when falsity occurs do something else. banana = (Banana.find(id).plantation.state rescue nil) || Fruit.find(:banana,id).state