No commit activity in last 3 years
No release in over 3 years
Like #delegate, but assumes the target method already exists, and delegates only when the local method returns nil
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

>= 0
 Project Readme

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

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request