module Yieldable
Yieldable
¶ ↑
This is meta-mixin, which makes your module, class or it's instance to respond to method to_proc
, for example, to easily build instances during iteration:
["1", "2", "3"].map(&SomeObject)
It is 2 different ways to use this module: extend
or prepend
it to your class.
extend Yieldable
¶ ↑
class SomeObject extend Yieldable # => singleton_class.to_proc = SomeObject.method(:call).to_proc end
This way defines an attribute reader to_proc
in a singleton class. It sets a proc only once for a class, so it will not generate a new Proc
object every time, like if you would use just a method(:call).to_proc
. By default it uses the call
class method as a source method for a proc. You can change the source method by using brackets:
class SomeObject extend Yieldable[:new] # => singleton_class.to_proc = SomeObject.method(:new).to_proc end
It's better to ensure that a source method is defined before extending a class with Yieldable
. In the other way it will add the singletone_method_added
hook and wait. After a source method will be added, the hook method will be removed.
You can avoid to removing the hook with an optional once: false
passed into the brackets:
extend Yieldable[:new, once: false]
prepend Yieldable
¶ ↑
This way defines a to_proc
instance method once for a class, but a proc will be generated once for each object. You can also use a brackets like within an extend
way.
Constants
- CallMixin
- VERSION
Public Class Methods
Creates configured mixin.
@param method_name [Symbol] A source method's name @param once [Boolean] Will be a proc defined only once? (by default: true
) @return [Module] the configured mixin
# File lib/yieldable.rb, line 48 def self.[](method_name = :call, once: true) Mixin.new(method_name, once: once) end
Utility to resolve method.
# File lib/yieldable.rb, line 53 def self.resolve_class_method(base, method_name) if base.respond_to?(method_name) base.method(method_name) else base.singleton_method(method_name) end end
Utility to set proc for the mixn.
# File lib/yieldable.rb, line 62 def self.set_proc(base, mixin) mixin.proc = resolve_class_method(base, mixin.method_name).to_proc base.instance_variable_set(:@to_proc, mixin.proc) base end
Private Class Methods
# File lib/yieldable.rb, line 162 def append_features(base) CallMixin.append_features(base) end
# File lib/yieldable.rb, line 154 def extend_object(base) CallMixin.extend_object(base) end
# File lib/yieldable.rb, line 158 def prepend_features(base) CallMixin.prepend_features(base) end