Module: Yieldable

Defined in:
lib/yieldable.rb,
lib/yieldable/version.rb

Overview

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.

Defined Under Namespace

Modules: Inheritance, InstanceMethodsMixin, ToProcReader, WaitMethodDefinition Classes: Mixin

Constant Summary collapse

CallMixin =
Mixin.new(:call)
VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.[](method_name = :call, once: true) ⇒ Module

Creates configured mixin.

Parameters:

  • method_name (Symbol) (defaults to: :call)

    A source method’s name

  • once (Boolean) (defaults to: true)

    Will be a proc defined only once? (by default: true)

Returns:

  • (Module)

    the configured mixin



48
49
50
# File 'lib/yieldable.rb', line 48

def self.[](method_name = :call, once: true)
  Mixin.new(method_name, once: once)
end

.resolve_class_method(base, method_name) ⇒ Object

Utility to resolve method.



53
54
55
56
57
58
59
# 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

.set_proc(base, mixin) ⇒ Object

Utility to set proc for the mixn.



62
63
64
65
66
# 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