Module: ExpressTemplates::Components::Capabilities::Iterating::ClassMethods

Defined in:
lib/express_templates/components/capabilities/iterating.rb

Instance Method Summary collapse

Instance Method Details

#for_each(iterator, as: :item, emit: :markup, empty: nil) ⇒ Object

Sets the component up to use iterating logic to reproduce a fragment for a collection.

Parameters include an iterator that may be :@variable assumed to be available in context or a proc that when evaluated in the context should return a collection.

An :emit option may specify a fragment to emit. Defaults to :markup

An :as option specifies the local variable name for each item in the collection for use in the fragment. Defaults to: item

An :empty option specifies a fragment to use for the empty state when the iterator returns an empty collection.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/express_templates/components/capabilities/iterating.rb', line 49

def for_each(iterator, as: :item, emit: :markup, empty: nil)
  as = as.to_sym
  emit = emit.to_sym
  iterator = iterator.kind_of?(Proc) ? iterator.source : iterator
  fragment_src = if empty
%Q(-> {
  unless_block(Proc.from_source("-> {#{iterator}.call.empty?}"), alt: #{self[empty].source}) {
    for_each(Proc.from_source("#{iterator}"), as: #{as.inspect}) {
      #{self[emit].source_body}
    }
  }
})
  else
%Q(-> {
  for_each(Proc.from_source("#{iterator}"), as: #{as.inspect}) {
    #{self[emit].source_body}
  }
})
  end
  fragment = Proc.from_source(fragment_src)
  _store :markup, fragment
end