Class: Enumerator::AutoForcedLazy
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- Enumerator::AutoForcedLazy
- Defined in:
- lib/enumerator.rb
Overview
Enumerator::AutoForcedLazy is a thin wrapper around Enumerator::Lazy that automatically calls Enumerator::Lazy#force before a method call if the called method does not exist on Enumerator::Lazy but exists on Array.
Enumerator::AutoForcedLazy can be constructed from any Enumerator::Lazy with the Enumerator::Lazy#auto_force method.
(1..Float::INFINITY).lazy.auto_force.take_while { |i| i < 30 }
=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:take_while>
Alternatively, Enumerator::AutoForcedLazy can also be constructed from any and from any Enumerable with the Enumerable#auto_forced_lazy method.
(1..Float::INFINITY).auto_forced_lazy.take_while { |i| i < 30 }
=> #<Enumerator::Lazy: #<Enumerator::Lazy: 1..Infinity>:take_while>
It is useful for keeping lazy enumerator semantics while providing easier access to Array methods by not requiring users to explicitly call Enumerator::Lazy#force.
Constant Summary collapse
- ARRAY_OBJ =
[].freeze
Instance Method Summary collapse
-
#initialize(lazy_enum) ⇒ AutoForcedLazy
constructor
A new instance of AutoForcedLazy.
-
#method_missing(m, *args, &block) ⇒ Object
rubocop:disable Style/MissingRespondToMissing.
Constructor Details
#initialize(lazy_enum) ⇒ AutoForcedLazy
Returns a new instance of AutoForcedLazy.
28 29 30 |
# File 'lib/enumerator.rb', line 28 def initialize(lazy_enum) super(lazy_enum) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args, &block) ⇒ Object
rubocop:disable Style/MissingRespondToMissing
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/enumerator.rb', line 33 def method_missing(m, *args, &block) if __getobj__.respond_to?(m) result = __getobj__.send(m, *args, &block) if result.is_a?(Enumerator::Lazy) __setobj__(result) self else result end elsif ARRAY_OBJ.respond_to?(m) __getobj__.force.send(m, *args, &block) else super end end |