项目作者: zverok

项目描述 :
delegate :methods, to: :target, extracted from ActiveSupport
高级语言: Ruby
项目地址: git://github.com/zverok/delegates.git
创建时间: 2020-06-09T17:22:19Z
项目社区:https://github.com/zverok/delegates

开源协议:

下载


Delegates

Gem Version
build

This gem is just an extraction of the handy delegate :method1, :method2, method3, to: :receiver from ActiveSupport. It seems to be seriously superior to stdlib’s Forwardable, and sometimes I want it in contexts when ActiveSupport and monkey-patching is undesireable.

Usage:

  1. gem install delegates

(or add gem 'delegates' to your Gemfile).

Then:

  1. class Employee < Struct.new(:name, :department, :address)
  2. # ...
  3. extend Delegates
  4. delegate :city, :street, to: :address
  5. # ...
  6. end
  7. employee = Employee.new(name, department, address)
  8. employee.city # will call employee.address.city

to: can be anything evaluatable from inside the class: :<CONSTANT>, :@<instance_variable>, 'chain.of.calls' etc.; special names requiring self (like class method) handled gracefully with just delegate ..., to: :class. New methods are defined with eval-ing strings, so they are as fast as if manually written.

Supported options examples (all that ActiveSupport’s Module#delegate supports):

  1. delegate :city, to: :address, prefix: true # defined method would be address_city
  2. delegate :city, to: :address, prefix: :adrs # defined method would be adrs_city
  3. delegate :city, to: :address, private: true # defined method would be private
  4. delegate :city, to: :address, allow_nil: true

The latter option will handle the employee.city call when employee.address is nil by returning nil; otherwise (by default) informative DelegationError is raised.

Credits

99.99% of credits should go to Rails users and contributors, who found and and handled miriads of realistic edge cases. I just copied the code (and groomed it a bit for closer to my own style).