Module: Bridgetown::Filters::ConditionHelpers

Included in:
Bridgetown::Filters, Tags::Find
Defined in:
bridgetown-core/lib/bridgetown-core/filters/condition_helpers.rb

Overview

The following set of code was adapted from Liquid::If ref: https://git.io/vp6K6

Instance Method Summary collapse

Instance Method Details

#parse_binary_comparison(parser) ⇒ Liquid::Condition

Generate a Liquid::Condition object from a Liquid::Parser object additionally processing the parsed expression based on whether the expression consists of binary operations with Liquid operators and or or

Parameters:

  • parser (Liquid::Parser)

Returns:

  • (Liquid::Condition)


23
24
25
26
27
28
29
30
31
32
# File 'bridgetown-core/lib/bridgetown-core/filters/condition_helpers.rb', line 23

def parse_binary_comparison(parser)
  condition = parse_comparison(parser)
  first_condition = condition
  while (binary_operator = parser.id?("and") || parser.id?("or"))
    child_condition = parse_comparison(parser)
    condition.send(binary_operator, child_condition)
    condition = child_condition
  end
  first_condition
end

#parse_comparison(parser) ⇒ Liquid::Condition

Generates a Liquid::Condition object from a Liquid::Parser object based on whether the parsed expression involves a “comparison” operator (e.g. <, ==, >, !=, etc)

Parameters:

  • parser (Liquid::Parser)

Returns:

  • (Liquid::Condition)


40
41
42
43
44
45
46
47
48
49
50
# File 'bridgetown-core/lib/bridgetown-core/filters/condition_helpers.rb', line 40

def parse_comparison(parser)
  left_operand = Liquid::Expression.parse(parser.expression)
  operator     = parser.consume?(:comparison)

  # No comparison-operator detected. Initialize a Liquid::Condition using only left operand
  return Liquid::Condition.new(left_operand) unless operator

  # Parse what remained after extracting the left operand and the `:comparison` operator
  # and initialize a Liquid::Condition object using the operands and the comparison-operator
  Liquid::Condition.new(left_operand, operator, Liquid::Expression.parse(parser.expression))
end

#parse_condition(exp) ⇒ Object

Parse a string to a Liquid Condition



9
10
11
12
13
14
15
# File 'bridgetown-core/lib/bridgetown-core/filters/condition_helpers.rb', line 9

def parse_condition(exp)
  parser    = Liquid::Parser.new(exp)
  condition = parse_binary_comparison(parser)

  parser.consume(:end_of_string)
  condition
end