Skip to content

Instantly share code, notes, and snippets.

@thegrubbsian
Created August 28, 2012 15:41
Show Gist options
  • Save thegrubbsian/3499234 to your computer and use it in GitHub Desktop.
Save thegrubbsian/3499234 to your computer and use it in GitHub Desktop.
Using Rails try() for chaining multiple methods
class Object
def try_all(*methods)
values = [self]
methods.each do |method|
value = values.last.try(method)
return nil if value.nil?
values << value
end
values.last
end
end
@thegrubbsian
Copy link
Author

This is not a great idea as it's only use is in cases where the Law of Demeter has probably already been broken. However, in rare cases, or when dealing with legacy code that's mid-refactor it can be helpful to avoid long chains of try(:this).try(:that) calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment