/
filters.rb
532 lines (464 loc) · 15.5 KB
/
filters.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# frozen_string_literal: true
require_all "jekyll/filters"
module Jekyll
module Filters
include URLFilters
include GroupingFilters
include DateFilters
# Convert a Markdown string into HTML output.
#
# input - The Markdown String to convert.
#
# Returns the HTML formatted String.
def markdownify(input)
@context.registers[:site].find_converter_instance(
Jekyll::Converters::Markdown
).convert(input.to_s)
end
# Convert quotes into smart quotes.
#
# input - The String to convert.
#
# Returns the smart-quotified String.
def smartify(input)
@context.registers[:site].find_converter_instance(
Jekyll::Converters::SmartyPants
).convert(input.to_s)
end
# Convert a Sass string into CSS output.
#
# input - The Sass String to convert.
#
# Returns the CSS formatted String.
def sassify(input)
@context.registers[:site].find_converter_instance(
Jekyll::Converters::Sass
).convert(input)
end
# Convert a Scss string into CSS output.
#
# input - The Scss String to convert.
#
# Returns the CSS formatted String.
def scssify(input)
@context.registers[:site].find_converter_instance(
Jekyll::Converters::Scss
).convert(input)
end
# Slugify a filename or title.
#
# input - The filename or title to slugify.
# mode - how string is slugified
#
# Returns the given filename or title as a lowercase URL String.
# See Utils.slugify for more detail.
def slugify(input, mode = nil)
Utils.slugify(input, :mode => mode)
end
# XML escape a string for use. Replaces any special characters with
# appropriate HTML entity replacements.
#
# input - The String to escape.
#
# Examples
#
# xml_escape('foo "bar" <baz>')
# # => "foo "bar" <baz>"
#
# Returns the escaped String.
def xml_escape(input)
input.to_s.encode(:xml => :attr).gsub(%r!\A"|"\Z!, "")
end
# CGI escape a string for use in a URL. Replaces any special characters
# with appropriate %XX replacements.
#
# input - The String to escape.
#
# Examples
#
# cgi_escape('foo,bar;baz?')
# # => "foo%2Cbar%3Bbaz%3F"
#
# Returns the escaped String.
def cgi_escape(input)
CGI.escape(input)
end
# URI escape a string.
#
# input - The String to escape.
#
# Examples
#
# uri_escape('foo, bar \\baz?')
# # => "foo,%20bar%20%5Cbaz?"
#
# Returns the escaped String.
def uri_escape(input)
Addressable::URI.normalize_component(input)
end
# Replace any whitespace in the input string with a single space
#
# input - The String on which to operate.
#
# Returns the formatted String
def normalize_whitespace(input)
input.to_s.gsub(%r!\s+!, " ").tap(&:strip!)
end
# Count the number of words in the input string.
#
# input - The String on which to operate.
#
# Returns the Integer word count.
def number_of_words(input, mode = nil)
cjk_charset = '\p{Han}\p{Katakana}\p{Hiragana}\p{Hangul}'
cjk_regex = %r![#{cjk_charset}]!o
word_regex = %r![^#{cjk_charset}\s]+!o
case mode
when "cjk"
input.scan(cjk_regex).length + input.scan(word_regex).length
when "auto"
cjk_count = input.scan(cjk_regex).length
cjk_count.zero? ? input.split.length : cjk_count + input.scan(word_regex).length
else
input.split.length
end
end
# Join an array of things into a string by separating with commas and the
# word "and" for the last one.
#
# array - The Array of Strings to join.
# connector - Word used to connect the last 2 items in the array
#
# Examples
#
# array_to_sentence_string(["apples", "oranges", "grapes"])
# # => "apples, oranges, and grapes"
#
# Returns the formatted String.
def array_to_sentence_string(array, connector = "and")
case array.length
when 0
""
when 1
array[0].to_s
when 2
"#{array[0]} #{connector} #{array[1]}"
else
"#{array[0...-1].join(", ")}, #{connector} #{array[-1]}"
end
end
# Convert the input into json string
#
# input - The Array or Hash to be converted
#
# Returns the converted json string
def jsonify(input)
as_liquid(input).to_json
end
# Filter an array of objects
#
# input - the object array.
# property - the property within each object to filter by.
# value - the desired value.
# Cannot be an instance of Array nor Hash since calling #to_s on them returns
# their `#inspect` string object.
#
# Returns the filtered array of objects
def where(input, property, value)
return input if !property || value.is_a?(Array) || value.is_a?(Hash)
return input unless input.respond_to?(:select)
input = input.values if input.is_a?(Hash)
input_id = input.hash
# implement a hash based on method parameters to cache the end-result
# for given parameters.
@where_filter_cache ||= {}
@where_filter_cache[input_id] ||= {}
@where_filter_cache[input_id][property] ||= {}
# stash or retrieve results to return
@where_filter_cache[input_id][property][value] ||= input.select do |object|
compare_property_vs_target(item_property(object, property), value)
end.to_a
end
# Filters an array of objects against an expression
#
# input - the object array
# variable - the variable to assign each item to in the expression
# expression - a Liquid comparison expression passed in as a string
#
# Returns the filtered array of objects
def where_exp(input, variable, expression)
return input unless input.respond_to?(:select)
input = input.values if input.is_a?(Hash) # FIXME
condition = parse_condition(expression)
@context.stack do
input.select do |object|
@context[variable] = object
condition.evaluate(@context)
end
end || []
end
# Search an array of objects and returns the first object that has the queried attribute
# with the given value or returns nil otherwise.
#
# input - the object array.
# property - the property within each object to search by.
# value - the desired value.
# Cannot be an instance of Array nor Hash since calling #to_s on them returns
# their `#inspect` string object.
#
# Returns the found object or nil
#
# rubocop:disable Metrics/CyclomaticComplexity
def find(input, property, value)
return input if !property || value.is_a?(Array) || value.is_a?(Hash)
return input unless input.respond_to?(:find)
input = input.values if input.is_a?(Hash)
input_id = input.hash
# implement a hash based on method parameters to cache the end-result for given parameters.
@find_filter_cache ||= {}
@find_filter_cache[input_id] ||= {}
@find_filter_cache[input_id][property] ||= {}
# stash or retrieve results to return
# Since `enum.find` can return nil or false, we use a placeholder string "<__NO MATCH__>"
# to validate caching.
result = @find_filter_cache[input_id][property][value] ||= input.find do |object|
compare_property_vs_target(item_property(object, property), value)
end || "<__NO MATCH__>"
return nil if result == "<__NO MATCH__>"
result
end
# rubocop:enable Metrics/CyclomaticComplexity
# Searches an array of objects against an expression and returns the first object for which
# the expression evaluates to true, or returns nil otherwise.
#
# input - the object array
# variable - the variable to assign each item to in the expression
# expression - a Liquid comparison expression passed in as a string
#
# Returns the found object or nil
def find_exp(input, variable, expression)
return input unless input.respond_to?(:find)
input = input.values if input.is_a?(Hash)
condition = parse_condition(expression)
@context.stack do
input.find do |object|
@context[variable] = object
condition.evaluate(@context)
end
end
end
# Convert the input into integer
#
# input - the object string
#
# Returns the integer value
def to_integer(input)
return 1 if input == true
return 0 if input == false
input.to_i
end
# Sort an array of objects
#
# input - the object array
# property - property within each object to filter by
# nils ('first' | 'last') - nils appear before or after non-nil values
#
# Returns the filtered array of objects
def sort(input, property = nil, nils = "first")
raise ArgumentError, "Cannot sort a null object." if input.nil?
if property.nil?
input.sort
else
case nils
when "first"
order = - 1
when "last"
order = + 1
else
raise ArgumentError, "Invalid nils order: " \
"'#{nils}' is not a valid nils order. It must be 'first' or 'last'."
end
sort_input(input, property, order)
end
end
def pop(array, num = 1)
return array unless array.is_a?(Array)
num = Liquid::Utils.to_integer(num)
new_ary = array.dup
new_ary.pop(num)
new_ary
end
def push(array, input)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.push(input)
new_ary
end
def shift(array, num = 1)
return array unless array.is_a?(Array)
num = Liquid::Utils.to_integer(num)
new_ary = array.dup
new_ary.shift(num)
new_ary
end
def unshift(array, input)
return array unless array.is_a?(Array)
new_ary = array.dup
new_ary.unshift(input)
new_ary
end
def sample(input, num = 1)
return input unless input.respond_to?(:sample)
num = Liquid::Utils.to_integer(num) rescue 1
if num == 1
input.sample
else
input.sample(num)
end
end
# Convert an object into its String representation for debugging
#
# input - The Object to be converted
#
# Returns a String representation of the object.
def inspect(input)
xml_escape(input.inspect)
end
private
# Sort the input Enumerable by the given property.
# If the property doesn't exist, return the sort order respective of
# which item doesn't have the property.
# We also utilize the Schwartzian transform to make this more efficient.
def sort_input(input, property, order)
input.map { |item| [item_property(item, property), item] }
.sort! do |a_info, b_info|
a_property = a_info.first
b_property = b_info.first
if !a_property.nil? && b_property.nil?
- order
elsif a_property.nil? && !b_property.nil?
+ order
else
a_property <=> b_property || a_property.to_s <=> b_property.to_s
end
end
.map!(&:last)
end
# `where` filter helper
#
def compare_property_vs_target(property, target)
case target
when NilClass
return true if property.nil?
when Liquid::Expression::MethodLiteral # `empty` or `blank`
target = target.to_s
return true if property == target || Array(property).join == target
else
target = target.to_s
if property.is_a? String
return true if property == target
else
Array(property).each do |prop|
return true if prop.to_s == target
end
end
end
false
end
def item_property(item, property)
@item_property_cache ||= @context.registers[:site].filter_cache[:item_property] ||= {}
@item_property_cache[property] ||= {}
@item_property_cache[property][item] ||= begin
property = property.to_s
property = if item.respond_to?(:to_liquid)
read_liquid_attribute(item.to_liquid, property)
elsif item.respond_to?(:data)
item.data[property]
else
item[property]
end
parse_sort_input(property)
end
end
def read_liquid_attribute(liquid_data, property)
return liquid_data[property] unless property.include?(".")
property.split(".").reduce(liquid_data) do |data, key|
data.respond_to?(:[]) && data[key]
end
end
FLOAT_LIKE = %r!\A\s*-?(?:\d+\.?\d*|\.\d+)\s*\Z!.freeze
INTEGER_LIKE = %r!\A\s*-?\d+\s*\Z!.freeze
private_constant :FLOAT_LIKE, :INTEGER_LIKE
# return numeric values as numbers for proper sorting
def parse_sort_input(property)
stringified = property.to_s
return property.to_i if INTEGER_LIKE.match?(stringified)
return property.to_f if FLOAT_LIKE.match?(stringified)
property
end
def as_liquid(item)
case item
when Hash
item.each_with_object({}) { |(k, v), result| result[as_liquid(k)] = as_liquid(v) }
when Array
item.map { |i| as_liquid(i) }
else
if item.respond_to?(:to_liquid)
liquidated = item.to_liquid
# prevent infinite recursion for simple types (which return `self`)
if liquidated == item
item
else
as_liquid(liquidated)
end
else
item
end
end
end
# ----------- The following set of code was *adapted* from Liquid::If
# ----------- ref: https://git.io/vp6K6
# Parse a string to a Liquid Condition
def parse_condition(exp)
parser = Liquid::Parser.new(exp)
condition = parse_binary_comparison(parser)
parser.consume(:end_of_string)
condition
end
# 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`
#
# - parser: an instance of Liquid::Parser
#
# Returns an instance of Liquid::Condition
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
# Generates a Liquid::Condition object from a Liquid::Parser object based on whether the parsed
# expression involves a "comparison" operator (e.g. <, ==, >, !=, etc)
#
# - parser: an instance of Liquid::Parser
#
# Returns an instance of Liquid::Condition
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
end
end
Liquid::Template.register_filter(
Jekyll::Filters
)