DelegateWhenNil
This gem provides a macro-method, #delegate_when_nil, which works kind of like #delegate, except it evaluates the expression locally first, and delegates to the target only if the local result is nil.
class Parent
attr_accessor :name, :address
...
end
class Child
attr_accessor :name, :address
delegate_when_nil :name, :address, to: :parent, prefix: :get
# equivalent to
# def get_name
# self.name || (parent && parent.get_name) # #get_name on Parent might delegate further...
# end
# use #stop option to avoid the prefix on the parent attribute (delegation "stops" at parent)
class Child
delegate_when_nil :name, :address, to: :parent, prefix: :get, stop: true
# equivalent to
# def get_name
# self.name || (parent && parent.name) # #name directly on parent instead of #get_name
# end
delegate_when_blank
delegate_when_blank works just like delegate_when_nil, except the criteria for delegation are
more open. This gem uses the not_blank gem to determine blankness, so the results are not exactly
in line with what you might expect if you are used to ActiveSupport's blank? implementation.
class Child
delegate_when_nil :last_name, to: :parent, prefix: :obtain
# equivalent to
# def obtain_last_name
# self.last_name.nb || (parent && parent.obtain_last_name)
# end
Installation
Add this line to your application's Gemfile:
gem 'delegate_when_nil'
And then execute:
$ bundle
Or install it yourself as:
$ gem install delegate_when_nil
Usage
DelegateWhenNil installs itself in Module so is available everywhere in your code.
class Widget < PopularFramework::Base
attr_accessor :parent
attr_accessor :description, :colour, :height
delegate_when_nil :description, :colour, :height, to: :parent, prefix: :get
...
In this example, if the #description, #colour, or #height properties are accessed and are nil, DelegateWhenNil will ask the #parent property instead.
p = Parent.new :description => "Woggle"
w = Widget.new :parent => p, :colour => :blue
w.get_description #=> "Woggle"
w.get_colour #=> :blue
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request