https://github.com/rickbutton/safe_nested_calls
Safely call nested objects in ruby
https://github.com/rickbutton/safe_nested_calls
Last synced: 3 months ago
JSON representation
Safely call nested objects in ruby
- Host: GitHub
- URL: https://github.com/rickbutton/safe_nested_calls
- Owner: rickbutton
- Created: 2012-02-24T05:25:44.000Z (over 13 years ago)
- Default Branch: master
- Last Pushed: 2012-02-25T03:04:58.000Z (over 13 years ago)
- Last Synced: 2025-02-12T23:29:11.966Z (5 months ago)
- Language: Ruby
- Homepage:
- Size: 97.7 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# safe_nested_calls #
This gem allows you to safely call nested methods
on an object, and not worry about whether or not
the methods are defined. It is very useful for
managing dynamically created objects that may not
have some methods defined.# Installation #
gem install 'safe_nested_calls'
If you are using Rails, then it will automatically load
on server start, but if not, somewhere in your code, put:require 'safe_nested_calls'
# Usage #
safe_nested_calls adds two extra methods to Object,
`nested_respond_to?` and `safe_nested_method`.### nested_respond_to? ###
if object.nested_respond_to?(:one, :two, :three)
which is equivalent toif object.respond_to? :one
if object.one.respond_to? :two
object.one.two.respond_to? :three
### safe_nested_method ###This method can call the actual nested method desired, with optional parameters
object.safe_nested_method(:one, :two, :three) => returns object.one.two.three
#### Parameters #####
To use parameters, use a hash of :method => args, where args are the method argumentsobject.safe_nested_method(:one => 1, :two => [1, 2], :three => [1,2,3])
which is equivalent to (would throw NoMethodError if a method wasn't defined)object.one(1).two(1,2).three(1,2,3)
If you need to call of mix of methods with and without parameters, set the arguments for
the methods without parameters to `:none`object.safe_nested_method(:get => :none, :increment => 4, :save => :none)
which is equivalent to (would throw NoMethodError if a method wasn't defined)object.get().increment(4).save()