Created
April 27, 2011 03:25
-
-
Save saturnflyer/943663 to your computer and use it in GitHub Desktop.
Method fallback
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
# Instead of writing ternary operators with respond_to?: | |
# obj.respond_to?(:method_one) ? obj.method_one : obj.method_two | |
# I want something simpler | |
class Object | |
def fallback(*args) | |
method_to_try = args.find{|meth| self.respond_to?(meth) && meth.to_s != __method__.to_s } | |
self.send(method_to_try) | |
end | |
alias trial fallback | |
alias trip fallback | |
end | |
obj = Object.new | |
# I'm not sure what method name I like here | |
puts obj.fallback(:hello, 'fallback', 'name', :to_s, 'inspect') # returns the output of :to_s | |
puts obj.trial(:hello, 'fallback', 'name', :to_s, 'inspect') # returns the output of :to_s | |
puts obj.trip(:hello, 'fallback', 'name', :to_s, 'inspect') # returns the output of :to_s |
Thanks, Derek.
My use case is in the scenario where you don't know the object that you'll have:
"This is the #{obj.fallback(:title, :name, :label, :to_s)}"
Where obj
could be a User, Car, Document or Whatever. A standard method would, of course, be better, but in the case where that's not available a fallback can fit the bill.
Of the three choices I like fallback more. I don't like the syntax of separating the arguments away from the method call though - I think a brave choice that would handle the 80% circumstance would be to assume these are getters that take no params, or that all methods take exactly the same params. If I found myself using this for ~3 methods that took different lists of params, I think the conventional code would win out for clarity.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sorry for the duplicates! I can't seem to edit or delete my comments.