Class: Shamu::Services::LazyTransform
- Inherits:
-
Object
- Object
- Shamu::Services::LazyTransform
- Includes:
- Enumerable
- Defined in:
- lib/shamu/services/lazy_transform.rb
Overview
Lazily transform one enumerable to another with shortcuts for common collection methods such as first, count, etc.
Instance Method Summary collapse
- #count(*args) ⇒ Integer (also: #size, #length)
-
#drop(n) ⇒ LazyTransform
A new LazyTransform skipping
nsource entries. -
#each {|object| ... } ⇒ self
Yields each transformed value from the original source to the block.
-
#empty? ⇒ Boolean
True if there are no source values.
-
#first(*args) ⇒ Object
Get the first transformed value without transforming the entire list.
-
#initialize(source) {|object| ... } ⇒ LazyTransform
constructor
A new instance of LazyTransform.
-
#take(n) ⇒ LazyTransform
A new LazyTransform taking only
nsource entries.
Constructor Details
#initialize(source) {|object| ... } ⇒ LazyTransform
Returns a new instance of LazyTransform.
13 14 15 16 |
# File 'lib/shamu/services/lazy_transform.rb', line 13 def initialize( source, &transformer ) @transformer = transformer @source = source end |
Instance Method Details
#count(*args) ⇒ Integer Also known as: size, length
30 31 32 33 34 35 36 |
# File 'lib/shamu/services/lazy_transform.rb', line 30 def count( *args ) if args.any? || block_given? super else source.count end end |
#drop(n) ⇒ LazyTransform
75 76 77 78 79 80 81 |
# File 'lib/shamu/services/lazy_transform.rb', line 75 def drop( n ) if transformed? super else self.class.new( source.drop( n ), &transformer ) end end |
#each {|object| ... } ⇒ self
Yields each transformed value from the original source to the block.
23 24 25 26 |
# File 'lib/shamu/services/lazy_transform.rb', line 23 def each( &block ) transformed.each( &block ) self end |
#empty? ⇒ Boolean
57 58 59 |
# File 'lib/shamu/services/lazy_transform.rb', line 57 def empty? source.empty? end |
#first(n) ⇒ Object #first ⇒ Object
Get the first transformed value without transforming the entire list.
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/shamu/services/lazy_transform.rb', line 44 def first( *args ) if args.any? super else return @first if defined? @first @first = begin value = source.first raise_if_not_transformed( transformer.call( [ value ] ) ).first unless value.nil? end end end |
#take(n) ⇒ LazyTransform
64 65 66 67 68 69 70 |
# File 'lib/shamu/services/lazy_transform.rb', line 64 def take( n ) if transformed? super else self.class.new( source.take( n ), &transformer ) end end |