class Bridgetown::Tags::Find

Constants

CONDITIONS_SEP
SYNTAX

Public Class Methods

new(tag_name, markup, tokens) click to toggle source
Calls superclass method
# File lib/bridgetown-core/tags/find.rb, line 12
      def initialize(tag_name, markup, tokens)
        super
        if markup.strip =~ SYNTAX
          @new_var_name = Regexp.last_match(1).strip
          @single_or_group = Regexp.last_match(2)
          @arr_name = Regexp.last_match(3).strip
          @conditions = process_conditions(Regexp.last_match(4).strip)
        else
          raise SyntaxError, <<~MSG
            Syntax Error in tag 'find' while parsing the following markup:

            #{markup}

            Valid syntax: find <varname> where|in <array>, <condition(s)>
          MSG
        end
      end

Public Instance Methods

render(context) click to toggle source
# File lib/bridgetown-core/tags/find.rb, line 30
def render(context)
  @group = lookup_variable(context, @arr_name)
  return "" unless @group.respond_to?(:select)

  @group = @group.values if @group.is_a?(Hash)

  expression = @conditions.split(CONDITIONS_SEP).map do |condition|
    "__find_tag_item__.#{condition.strip}"
  end.join(" and ")
  @liquid_condition = parse_condition(expression)

  context[@new_var_name] = if @single_or_group == "where"
                             group_evaluate(context)
                           else
                             single_evaluate(context)
                           end

  ""
end

Private Instance Methods

group_evaluate(context) click to toggle source
# File lib/bridgetown-core/tags/find.rb, line 65
def group_evaluate(context)
  context.stack do
    @group.select do |object|
      context["__find_tag_item__"] = object
      @liquid_condition.evaluate(context)
    end
  end || []
end
process_conditions(conditions) click to toggle source
# File lib/bridgetown-core/tags/find.rb, line 52
def process_conditions(conditions)
  processed_conditions = +""
  in_quotes = false

  conditions.each_char do |c|
    in_quotes = !in_quotes if c == '"'

    processed_conditions << (c == "," && !in_quotes ? CONDITIONS_SEP : c)
  end

  processed_conditions
end
single_evaluate(context) click to toggle source
# File lib/bridgetown-core/tags/find.rb, line 74
def single_evaluate(context)
  context.stack do
    @group.find do |object|
      context["__find_tag_item__"] = object
      @liquid_condition.evaluate(context)
    end
  end || nil
end