Sha256: ee4a582e9184943e94896e84c8bf42508b74366032d90a9831fb32c04e131362

Contents?: true

Size: 1.87 KB

Versions: 11

Compression:

Stored size: 1.87 KB

Contents

module Locomotive
  module Steam
    module Liquid
      module Tags

        # Filter a collection
        #
        # Usage:
        #
        # {% with_scope main_developer: 'John Doe', providers.in: ['acme'], started_at.le: today, active: true %}
        #   {% for project in contents.projects %}
        #     {{ project.name }}
        #   {% endfor %}
        # {% endwith_scope %}
        #

        class WithScope < Solid::Block

          OPERATORS = %w(all exists gt gte in lt lte ne nin size near within)

          SYMBOL_OPERATORS_REGEXP = /(\w+\.(#{OPERATORS.join('|')})){1}\s*\:/o

          # register the tag
          tag_name :with_scope

          def initialize(name, markup, options)
            # convert symbol operators into valid ruby code
            markup.gsub!(SYMBOL_OPERATORS_REGEXP, ':"\1" =>')

            super(name, markup, options)
          end

          def display(options = {}, &block)
            current_context.stack do
              current_context['with_scope'] = self.decode(options)
              current_context['with_scope_content_type'] = false # for now, no content type is assigned to this with_scope
              yield
            end
          end

          protected

          def decode(options)
            HashWithIndifferentAccess.new.tap do |hash|
              options.each do |key, value|
                # _slug instead of _permalink
                _key = key.to_s == '_permalink' ? '_slug' : key.to_s

                hash[_key] = cast_value(value)
              end
            end
          end

          def cast_value(value)
            case value
            when Array then value.map { |_value| cast_value(_value) }
            when /^\/[^\/]*\/$/ then Regexp.new(value[1..-2])
            else
              value.respond_to?(:_id) ? value.send(:_source) : value
            end
          end

        end

      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
locomotivecms_steam-1.1.2 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.2.0.beta1 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.1.1 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.1.0 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.1.0.rc3 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.1.0.rc2 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.1.0.rc1 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.0.1 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.0.0 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.0.0.rc10 lib/locomotive/steam/liquid/tags/with_scope.rb
locomotivecms_steam-1.0.0.rc9 lib/locomotive/steam/liquid/tags/with_scope.rb