Sha256: ca2dbf6df7056276681ca85c2c3ad6fe2638f14d23f3b8ab05e60cbc40a1b41a

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

module ExpressTemplates
  module Components
    module Capabilities

      # Provides iteration to components that iterate over a collection.

      module Iteration

        def self.included(base)
          base.class_eval do

            # Iterates over the collection calling the block provided to emit markup.
            #
            # The collection (symbol) must be available as a method on the component
            # or as a local (assigns) value in the rendering context.
            #
            # The collection name is singularized and a local value is set
            # for each item in the collection.

            def for_all(collection_name, &block)
              @collection_name = collection_name
              raise "#{collection_name} is not a collection" unless self.send(collection_name).respond_to?(:each)
              self.send(collection_name).each do |item|
                old_value = assigns[singular_item_name]
                assigns[singular_item_name] = item
                block.call
                assigns[singular_item_name] = old_value
              end
            end

            protected

              def collection_name
                @collection_name
              end

              def singular_item_name
                collection_name.to_s.singularize.to_sym
              end

              def item
                assigns[singular_item_name]
              end

          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
express_templates-0.11.18 lib/express_templates/components/capabilities/iteration.rb