Skip to content

Instantly share code, notes, and snippets.

@saturnflyer
Created April 27, 2011 03:25
Show Gist options
  • Save saturnflyer/943663 to your computer and use it in GitHub Desktop.
Save saturnflyer/943663 to your computer and use it in GitHub Desktop.
Method fallback
# 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
@saturnflyer
Copy link
Author

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.

@bokmann
Copy link

bokmann commented Apr 27, 2011

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