Class: Liquid2::Filter

Inherits:
Expression show all
Defined in:
lib/liquid2/expressions/filtered.rb

Overview

A Liquid filter with a name and array of arguments.

Instance Attribute Summary collapse

Attributes inherited from Expression

#token

Instance Method Summary collapse

Methods inherited from Expression

#scope

Constructor Details

#initialize(token, name, args) ⇒ Filter

Returns a new instance of Filter.

Parameters:



87
88
89
90
91
# File 'lib/liquid2/expressions/filtered.rb', line 87

def initialize(token, name, args)
  super(token)
  @name = name
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



83
84
85
# File 'lib/liquid2/expressions/filtered.rb', line 83

def args
  @args
end

#nameObject (readonly)

Returns the value of attribute name.



83
84
85
# File 'lib/liquid2/expressions/filtered.rb', line 83

def name
  @name
end

Instance Method Details

#childrenObject



128
# File 'lib/liquid2/expressions/filtered.rb', line 128

def children = @args || []

#evaluate(left, context) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/liquid2/expressions/filtered.rb', line 93

def evaluate(left, context)
  filter, with_context = context.env.filters[@name]
  raise LiquidFilterNotFoundError.new("unknown filter #{@name.inspect}", @token) unless filter

  return filter.call(left) if @args.nil? && !with_context # steep:ignore
  return filter.call(left, context: context) if @args.nil? && with_context # steep:ignore

  positional_args = [] # @type var positional_args: Array[untyped]
  keyword_args = {} # @type var keyword_args: Hash[Symbol, untyped]

  index = 0
  loop do
    # `@args[index]` could be `false` or `nil`
    break if index >= @args.length # steep:ignore

    arg = @args[index] # steep:ignore
    index += 1
    if arg.respond_to?(:sym)
      keyword_args[arg.sym] = context.evaluate(arg.value)
    else
      positional_args << context.evaluate(arg)
    end
  end

  keyword_args[:context] = context if with_context

  if keyword_args.empty?
    filter.call(left, *positional_args) # steep:ignore
  else
    filter.call(left, *positional_args, **keyword_args) # steep:ignore
  end
rescue ArgumentError, TypeError => e
  raise LiquidArgumentError.new(e.message, @token)
end