Last active
August 29, 2015 14:01
-
-
Save tlux/f28ddaee391a9b9148c3 to your computer and use it in GitHub Desktop.
Object#try_first returns the result of the first responding method specified in an Array
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
| # Usage: | |
| # | |
| # object = MyObject.new | |
| # object.label = "Some content here..." | |
| # | |
| # object.try_first([:name, :label, :caption]) # => "Some content here..." | |
| # object.try_first(:description) # => nil | |
| class Object | |
| def try_first(method_names, *args, &block) | |
| method_name = Array(method_names).find { |method_name| respond_to?(method_name) } | |
| public_send(method_name, *args, &block) if method_name | |
| end | |
| def try_last(method_names, *args, &block) | |
| try_first(method_names.reverse, *args, &block) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment