Module: Liquid::StandardFilters

Defined in:
lib/liquid/standardfilters.rb

Defined Under Namespace

Classes: InputIterator

Constant Summary collapse

HTML_ESCAPE =
{
  '&' => '&',
  '>' => '>',
  '<' => '&lt;',
  '"' => '&quot;',
  "'" => '&#39;',
}.freeze
HTML_ESCAPE_ONCE_REGEXP =
/["><']|&(?!([a-zA-Z]+|(#\d+));)/
STRIP_HTML_BLOCKS =
Regexp.union(
  %r{<script.*?</script>}m,
  /<!--.*?-->/m,
  %r{<style.*?</style>}m
)
STRIP_HTML_TAGS =
/<.*?>/m

Instance Method Summary collapse

Instance Method Details

#abs(input) ⇒ Object

absolute value


361
362
363
364
# File 'lib/liquid/standardfilters.rb', line 361

def abs(input)
  result = Utils.to_number(input).abs
  result.is_a?(BigDecimal) ? result.to_f : result
end

#append(input, string) ⇒ Object

add one string to another


282
283
284
# File 'lib/liquid/standardfilters.rb', line 282

def append(input, string)
  input.to_s + string.to_s
end

#at_least(input, n) ⇒ Object


415
416
417
418
419
420
421
# File 'lib/liquid/standardfilters.rb', line 415

def at_least(input, n)
  min_value = Utils.to_number(n)

  result = Utils.to_number(input)
  result = min_value if min_value > result
  result.is_a?(BigDecimal) ? result.to_f : result
end

#at_most(input, n) ⇒ Object


423
424
425
426
427
428
429
# File 'lib/liquid/standardfilters.rb', line 423

def at_most(input, n)
  max_value = Utils.to_number(n)

  result = Utils.to_number(input)
  result = max_value if max_value < result
  result.is_a?(BigDecimal) ? result.to_f : result
end

#capitalize(input) ⇒ Object

capitalize words in the input centence


39
40
41
# File 'lib/liquid/standardfilters.rb', line 39

def capitalize(input)
  input.to_s.capitalize
end

#ceil(input) ⇒ Object


403
404
405
406
407
# File 'lib/liquid/standardfilters.rb', line 403

def ceil(input)
  Utils.to_number(input).ceil.to_i
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end

#compact(input, property = nil) ⇒ Object

Remove nils within an array provide optional property with which to check for nil


245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/liquid/standardfilters.rb', line 245

def compact(input, property = nil)
  ary = InputIterator.new(input, context)

  if property.nil?
    ary.compact
  elsif ary.empty? # The next two cases assume a non-empty array.
    []
  elsif ary.first.respond_to?(:[])
    begin
      ary.reject { |a| a[property].nil? }
    rescue TypeError
      raise_property_error(property)
    end
  end
end

#concat(input, array) ⇒ Object


286
287
288
289
290
291
# File 'lib/liquid/standardfilters.rb', line 286

def concat(input, array)
  unless array.respond_to?(:to_ary)
    raise ArgumentError, "concat filter requires an array argument"
  end
  InputIterator.new(input, context).concat(array)
end

#date(input, format) ⇒ Object

Reformat a date using Ruby's core Time#strftime( string ) -> string

%a - The abbreviated weekday name (``Sun'')
%A - The  full  weekday  name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The  full  month  name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM''  or  ``PM'')
%s - Number of seconds since 1970-01-01 00:00:00 UTC.
%S - Second of the minute (00..60)
%U - Week  number  of the current year,
        starting with the first Sunday as the first
        day of the first week (00..53)
%W - Week  number  of the current year,
        starting with the first Monday as the first
        day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

See also: http://www.ruby-doc.org/core/Time.html#method-i-strftime

334
335
336
337
338
339
340
# File 'lib/liquid/standardfilters.rb', line 334

def date(input, format)
  return input if format.to_s.empty?

  return input unless (date = Utils.to_date(input))

  date.strftime(format.to_s)
end

#default(input, default_value = '', options = {}) ⇒ Object

Set a default value when the input is nil, false or empty

Example:

{{ product.title | default: "No Title" }}

Use `allow_false` when an input should only be tested against nil or empty and not false.

Example:

{{ product.title | default: "No Title", allow_false: true }}

441
442
443
444
445
# File 'lib/liquid/standardfilters.rb', line 441

def default(input, default_value = '', options = {})
  options = {} unless options.is_a?(Hash)
  false_check = options['allow_false'] ? input.nil? : !input
  false_check || (input.respond_to?(:empty?) && input.empty?) ? default_value : input
end

#divided_by(input, operand) ⇒ Object

division


382
383
384
385
386
# File 'lib/liquid/standardfilters.rb', line 382

def divided_by(input, operand)
  apply_operation(input, operand, :/)
rescue ::ZeroDivisionError => e
  raise Liquid::ZeroDivisionError, e.message
end

#downcase(input) ⇒ Object

convert an input string to DOWNCASE


29
30
31
# File 'lib/liquid/standardfilters.rb', line 29

def downcase(input)
  input.to_s.downcase
end

#escape(input) ⇒ Object Also known as: h


43
44
45
# File 'lib/liquid/standardfilters.rb', line 43

def escape(input)
  CGI.escapeHTML(input.to_s) unless input.nil?
end

#escape_once(input) ⇒ Object


48
49
50
# File 'lib/liquid/standardfilters.rb', line 48

def escape_once(input)
  input.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
end

#first(array) ⇒ Object

Get the first element of the passed in array

Example:

{{ product.images | first | to_img }}

347
348
349
# File 'lib/liquid/standardfilters.rb', line 347

def first(array)
  array.first if array.respond_to?(:first)
end

#floor(input) ⇒ Object


409
410
411
412
413
# File 'lib/liquid/standardfilters.rb', line 409

def floor(input)
  Utils.to_number(input).floor.to_i
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end

#join(input, glue = ' ') ⇒ Object

Join elements of the array with certain character between them


137
138
139
# File 'lib/liquid/standardfilters.rb', line 137

def join(input, glue = ' ')
  InputIterator.new(input, context).join(glue)
end

#last(array) ⇒ Object

Get the last element of the passed in array

Example:

{{ product.images | last | to_img }}

356
357
358
# File 'lib/liquid/standardfilters.rb', line 356

def last(array)
  array.last if array.respond_to?(:last)
end

#lstrip(input) ⇒ Object


116
117
118
# File 'lib/liquid/standardfilters.rb', line 116

def lstrip(input)
  input.to_s.lstrip
end

#map(input, property) ⇒ Object

map/collect on a given property


228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/liquid/standardfilters.rb', line 228

def map(input, property)
  InputIterator.new(input, context).map do |e|
    e = e.call if e.is_a?(Proc)

    if property == "to_liquid"
      e
    elsif e.respond_to?(:[])
      r = e[property]
      r.is_a?(Proc) ? r.call : r
    end
  end
rescue TypeError
  raise_property_error(property)
end

#minus(input, operand) ⇒ Object

subtraction


372
373
374
# File 'lib/liquid/standardfilters.rb', line 372

def minus(input, operand)
  apply_operation(input, operand, :-)
end

#modulo(input, operand) ⇒ Object


388
389
390
391
392
# File 'lib/liquid/standardfilters.rb', line 388

def modulo(input, operand)
  apply_operation(input, operand, :%)
rescue ::ZeroDivisionError => e
  raise Liquid::ZeroDivisionError, e.message
end

#newline_to_br(input) ⇒ Object

Add <br /> tags in front of all newlines in input string


299
300
301
# File 'lib/liquid/standardfilters.rb', line 299

def newline_to_br(input)
  input.to_s.gsub(/\r?\n/, "<br />\n")
end

#plus(input, operand) ⇒ Object

addition


367
368
369
# File 'lib/liquid/standardfilters.rb', line 367

def plus(input, operand)
  apply_operation(input, operand, :+)
end

#prepend(input, string) ⇒ Object

prepend a string to another


294
295
296
# File 'lib/liquid/standardfilters.rb', line 294

def prepend(input, string)
  string.to_s + input.to_s
end

#remove(input, string) ⇒ Object

remove a substring


272
273
274
# File 'lib/liquid/standardfilters.rb', line 272

def remove(input, string)
  input.to_s.gsub(string.to_s, '')
end

#remove_first(input, string) ⇒ Object

remove the first occurrences of a substring


277
278
279
# File 'lib/liquid/standardfilters.rb', line 277

def remove_first(input, string)
  input.to_s.sub(string.to_s, '')
end

#replace(input, string, replacement = '') ⇒ Object

Replace occurrences of a string with another


262
263
264
# File 'lib/liquid/standardfilters.rb', line 262

def replace(input, string, replacement = '')
  input.to_s.gsub(string.to_s, replacement.to_s)
end

#replace_first(input, string, replacement = '') ⇒ Object

Replace the first occurrences of a string with another


267
268
269
# File 'lib/liquid/standardfilters.rb', line 267

def replace_first(input, string, replacement = '')
  input.to_s.sub(string.to_s, replacement.to_s)
end

#reverse(input) ⇒ Object

Reverse the elements of an array


222
223
224
225
# File 'lib/liquid/standardfilters.rb', line 222

def reverse(input)
  ary = InputIterator.new(input, context)
  ary.reverse
end

#round(input, n = 0) ⇒ Object


394
395
396
397
398
399
400
401
# File 'lib/liquid/standardfilters.rb', line 394

def round(input, n = 0)
  result = Utils.to_number(input).round(Utils.to_number(n))
  result = result.to_f if result.is_a?(BigDecimal)
  result = result.to_i if n == 0
  result
rescue ::FloatDomainError => e
  raise Liquid::FloatDomainError, e.message
end

#rstrip(input) ⇒ Object


120
121
122
# File 'lib/liquid/standardfilters.rb', line 120

def rstrip(input)
  input.to_s.rstrip
end

#size(input) ⇒ Object

Return the size of an array or of an string


24
25
26
# File 'lib/liquid/standardfilters.rb', line 24

def size(input)
  input.respond_to?(:size) ? input.size : 0
end

#slice(input, offset, length = nil) ⇒ Object


65
66
67
68
69
70
71
72
73
74
# File 'lib/liquid/standardfilters.rb', line 65

def slice(input, offset, length = nil)
  offset = Utils.to_integer(offset)
  length = length ? Utils.to_integer(length) : 1

  if input.is_a?(Array)
    input.slice(offset, length) || []
  else
    input.to_s.slice(offset, length) || ''
  end
end

#sort(input, property = nil) ⇒ Object

Sort elements of the array provide optional property with which to sort an array of hashes or drops


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/liquid/standardfilters.rb', line 143

def sort(input, property = nil)
  ary = InputIterator.new(input, context)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      nil_safe_compare(a, b)
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| nil_safe_compare(a[property], b[property]) }
    rescue TypeError
      raise_property_error(property)
    end
  end
end

#sort_natural(input, property = nil) ⇒ Object

Sort elements of an array ignoring case if strings provide optional property with which to sort an array of hashes or drops


163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/liquid/standardfilters.rb', line 163

def sort_natural(input, property = nil)
  ary = InputIterator.new(input, context)

  return [] if ary.empty?

  if property.nil?
    ary.sort do |a, b|
      nil_safe_casecmp(a, b)
    end
  elsif ary.all? { |el| el.respond_to?(:[]) }
    begin
      ary.sort { |a, b| nil_safe_casecmp(a[property], b[property]) }
    rescue TypeError
      raise_property_error(property)
    end
  end
end

#split(input, pattern) ⇒ Object

Split input string into an array of substrings separated by given pattern.

Example:

<div class="summary">{{ post | split '//' | first }}</div>

108
109
110
# File 'lib/liquid/standardfilters.rb', line 108

def split(input, pattern)
  input.to_s.split(pattern.to_s)
end

#strip(input) ⇒ Object


112
113
114
# File 'lib/liquid/standardfilters.rb', line 112

def strip(input)
  input.to_s.strip
end

#strip_html(input) ⇒ Object


124
125
126
127
128
129
# File 'lib/liquid/standardfilters.rb', line 124

def strip_html(input)
  empty  = ''
  result = input.to_s.gsub(STRIP_HTML_BLOCKS, empty)
  result.gsub!(STRIP_HTML_TAGS, empty)
  result
end

#strip_newlines(input) ⇒ Object

Remove all newlines from the string


132
133
134
# File 'lib/liquid/standardfilters.rb', line 132

def strip_newlines(input)
  input.to_s.gsub(/\r?\n/, '')
end

#times(input, operand) ⇒ Object

multiplication


377
378
379
# File 'lib/liquid/standardfilters.rb', line 377

def times(input, operand)
  apply_operation(input, operand, :*)
end

#truncate(input, length = 50, truncate_string = "...") ⇒ Object

Truncate a string down to x characters


77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/liquid/standardfilters.rb', line 77

def truncate(input, length = 50, truncate_string = "...")
  return if input.nil?
  input_str = input.to_s
  length    = Utils.to_integer(length)

  truncate_string_str = truncate_string.to_s

  l = length - truncate_string_str.length
  l = 0 if l < 0

  input_str.length > length ? input_str[0...l].concat(truncate_string_str) : input_str
end

#truncatewords(input, words = 15, truncate_string = "...") ⇒ Object


90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/liquid/standardfilters.rb', line 90

def truncatewords(input, words = 15, truncate_string = "...")
  return if input.nil?
  input = input.to_s
  words = Utils.to_integer(words)
  words = 1 if words <= 0

  wordlist = input.split(" ", words + 1)
  return input if wordlist.length <= words

  wordlist.pop
  wordlist.join(" ").concat(truncate_string.to_s)
end

#uniq(input, property = nil) ⇒ Object

Remove duplicate elements from an array provide optional property with which to determine uniqueness


205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/liquid/standardfilters.rb', line 205

def uniq(input, property = nil)
  ary = InputIterator.new(input, context)

  if property.nil?
    ary.uniq
  elsif ary.empty? # The next two cases assume a non-empty array.
    []
  elsif ary.first.respond_to?(:[])
    begin
      ary.uniq { |a| a[property] }
    rescue TypeError
      raise_property_error(property)
    end
  end
end

#upcase(input) ⇒ Object

convert an input string to UPCASE


34
35
36
# File 'lib/liquid/standardfilters.rb', line 34

def upcase(input)
  input.to_s.upcase
end

#url_decode(input) ⇒ Object


56
57
58
59
60
61
62
63
# File 'lib/liquid/standardfilters.rb', line 56

def url_decode(input)
  return if input.nil?

  result = CGI.unescape(input.to_s)
  raise Liquid::ArgumentError, "invalid byte sequence in #{result.encoding}" unless result.valid_encoding?

  result
end

#url_encode(input) ⇒ Object


52
53
54
# File 'lib/liquid/standardfilters.rb', line 52

def url_encode(input)
  CGI.escape(input.to_s) unless input.nil?
end

#where(input, property, target_value = nil) ⇒ Object

Filter the elements of an array to those with a certain property value. By default the target is any truthy value.


183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/liquid/standardfilters.rb', line 183

def where(input, property, target_value = nil)
  ary = InputIterator.new(input, context)

  if ary.empty?
    []
  elsif ary.first.respond_to?(:[]) && target_value.nil?
    begin
      ary.select { |item| item[property] }
    rescue TypeError
      raise_property_error(property)
    end
  elsif ary.first.respond_to?(:[])
    begin
      ary.select { |item| item[property] == target_value }
    rescue TypeError
      raise_property_error(property)
    end
  end
end