Module: Bridgetown::Filters

Includes:
ConditionHelpers, DateFilters, GroupingFilters, LocalizationFilters, TranslationFilters, URLFilters
Included in:
RubyTemplateView::Helpers
Defined in:
lib/bridgetown-core/filters.rb,
lib/bridgetown-core/filters/from_liquid.rb,
lib/bridgetown-core/filters/url_filters.rb,
lib/bridgetown-core/filters/date_filters.rb,
lib/bridgetown-core/filters/grouping_filters.rb,
lib/bridgetown-core/filters/condition_helpers.rb,
lib/bridgetown-core/filters/translation_filters.rb,
lib/bridgetown-core/filters/localization_filters.rb

Defined Under Namespace

Modules: ConditionHelpers, DateFilters, FromLiquid, GroupingFilters, LocalizationFilters, TranslationFilters, URLFilters

Instance Method Summary collapse

Methods included from ConditionHelpers

#parse_binary_comparison, #parse_comparison, #parse_condition

Methods included from TranslationFilters

#t

Methods included from LocalizationFilters

#l

Methods included from DateFilters

#date_to_long_string, #date_to_rfc822, #date_to_string, #date_to_xmlschema

Methods included from GroupingFilters

#group_by, #group_by_exp

Methods included from URLFilters

#absolute_url, #in_locale, #relative_url, #strip_extname, #strip_index

Instance Method Details

#array_to_sentence_string(array, connector = "and") ⇒ String

Join an array of things into a string by separating with commas and the word "and" for the last one

Examples:

array_to_sentence_string(["apples", "oranges", "grapes"])
# => "apples, oranges, and grapes"

Parameters:

  • array (Array<String>)
  • connector (String) (defaults to: "and")

    word used to connect the last 2 items in the array

Returns:

  • (String)


140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/bridgetown-core/filters.rb', line 140

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

#cgi_escape(input) ⇒ String

CGI escape a string for use in a URL. Replaces any special characters with appropriate %XX replacements.

Examples:

cgi_escape('foo,bar;baz?')
# => "foo%2Cbar%3Bbaz%3F"

Parameters:

  • input (String)

Returns:

  • (String)


74
75
76
# File 'lib/bridgetown-core/filters.rb', line 74

def cgi_escape(input)
  CGI.escape(input.to_s)
end

#inspect(input = nil) ⇒ String

Convert an object into its String representation for debugging

Parameters:

  • input (Object) (defaults to: nil)

    The Object to be converted

Returns:

  • (String)

    the representation of the object.



293
294
295
296
297
# File 'lib/bridgetown-core/filters.rb', line 293

def inspect(input = nil)
  return super() if input.nil?

  xml_escape(input.inspect)
end

#jsonify(input) ⇒ String

Convert the input into JSON string

Parameters:

  • input (Array, Hash, String, Integer)

Returns:

  • (String)

    JSON string



157
158
159
# File 'lib/bridgetown-core/filters.rb', line 157

def jsonify(input)
  as_liquid(input).to_json
end

#markdownify(input) ⇒ String

Convert a Markdown string into HTML output

Parameters:

  • input (String)

Returns:

  • (String)

    HTML formatted text



18
19
20
21
22
# File 'lib/bridgetown-core/filters.rb', line 18

def markdownify(input)
  @context.registers[:site].find_converter_instance(
    Bridgetown::Converters::Markdown
  ).convert(input.to_s)
end

#normalize_whitespace(input) ⇒ String

Replace any whitespace in the input string with a single space

Parameters:

  • input (String)

Returns:

  • (String)


109
110
111
# File 'lib/bridgetown-core/filters.rb', line 109

def normalize_whitespace(input)
  input.to_s.gsub(%r!\s+!, " ").strip
end

#number_of_words(input) ⇒ Integer

Count the number of words in the input string.

Parameters:

  • input (String)

Returns:

  • (Integer)

    word count



117
118
119
# File 'lib/bridgetown-core/filters.rb', line 117

def number_of_words(input)
  input.split.length
end

Obfuscate an email, telephone number etc.

Parameters:

  • input (String)

    the String containing the contact information (email, phone etc.)

  • prefix (String) (defaults to: "mailto")

    the URL scheme to prefix (default "mailto")

Returns:

  • (String)

    a link unreadable for bots but will be recovered on focus or mouseover



95
96
97
98
99
100
101
102
103
# File 'lib/bridgetown-core/filters.rb', line 95

def obfuscate_link(input, prefix = "mailto")
  link = "<a href=\"#{prefix}:#{input}\">#{input}</a>"
  script = "<script type=\"text/javascript\">document.currentScript.insertAdjacentHTML('"
  script += "beforebegin', '#{rot47(link).gsub("\\", '\\\\\\')}'.replace(/[!-~]/g," # rubocop:disable Style/StringLiteralsInInterpolation
  script += "function(c){{var j=c.charCodeAt(0);if((j>=33)&&(j<=126)){"
  script += "return String.fromCharCode(33+((j+ 14)%94));}"
  script += "else{return String.fromCharCode(j);}}}));</script>"
  script.html_safe
end

#pop(array, num = 1) ⇒ Object



243
244
245
246
247
248
249
250
# File 'lib/bridgetown-core/filters.rb', line 243

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

#push(array, input) ⇒ Object



252
253
254
255
256
257
258
# File 'lib/bridgetown-core/filters.rb', line 252

def push(array, input)
  return array unless array.is_a?(Array)

  new_ary = array.dup
  new_ary.push(input)
  new_ary
end

#reading_time(input, round_to = 0) ⇒ Float

Calculates the average reading time of the supplied content

Parameters:

  • input (String)

    the String of content to analyze.

Returns:

  • (Float)

    the number of minutes required to read the content.



125
126
127
128
# File 'lib/bridgetown-core/filters.rb', line 125

def reading_time(input, round_to = 0)
  wpm = @context.registers[:site].config[:reading_time_wpm] || 250
  (number_of_words(input).to_f / wpm).ceil(round_to)
end

#sample(input, num = 1) ⇒ Object



277
278
279
280
281
282
283
284
285
286
# File 'lib/bridgetown-core/filters.rb', line 277

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

#shift(array, num = 1) ⇒ Object



260
261
262
263
264
265
266
267
# File 'lib/bridgetown-core/filters.rb', line 260

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

#slugify(input, mode = nil) ⇒ String

Slugify a filename or title

Parameters:

  • input (String)

    the filename or title to slugify

  • mode (String) (defaults to: nil)

    how string is slugified

Returns:

  • (String)

    lowercase URL

See Also:



38
39
40
41
# File 'lib/bridgetown-core/filters.rb', line 38

def slugify(input, mode = nil)
  mode = @context.registers[:site].config.slugify_mode if mode.nil?
  Utils.slugify(input, mode:)
end

#smartify(input) ⇒ String

Convert quotes into smart quotes

Parameters:

  • input (String)

Returns:

  • (String)

    smart-quotified text



28
29
30
# File 'lib/bridgetown-core/filters.rb', line 28

def smartify(input)
  Utils::SmartyPantsConverter.new(@context.registers[:site].config).convert(input.to_s)
end

#sort(input, property = nil, nils = "first") ⇒ Array

Sort an array of objects

Parameters:

  • input (Array)
  • property (String) (defaults to: nil)

    the property within each object to filter by

  • nils (String) (defaults to: "first")

    first | last (nils appear before or after non-nil values)

Returns:

  • (Array)

    sorted array of objects

Raises:

  • (ArgumentError)


223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/bridgetown-core/filters.rb', line 223

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

#titleize(input) ⇒ String

Titleize a slug or identifier string.

Parameters:

  • input (String)

Returns:

  • (String)

    transformed string with spaces and capitalized words

See Also:



48
49
50
# File 'lib/bridgetown-core/filters.rb', line 48

def titleize(input)
  Utils.titleize_slug(input)
end

#to_integer(input) ⇒ Integer

Convert the input into integer

Parameters:

  • input (String, Boolean)

    if boolean, 1 for true and 0 for false

Returns:

  • (Integer)


210
211
212
213
214
215
# File 'lib/bridgetown-core/filters.rb', line 210

def to_integer(input)
  return 1 if input == true
  return 0 if input == false

  input.to_i
end

#unshift(array, input) ⇒ Object



269
270
271
272
273
274
275
# File 'lib/bridgetown-core/filters.rb', line 269

def unshift(array, input)
  return array unless array.is_a?(Array)

  new_ary = array.dup
  new_ary.unshift(input)
  new_ary
end

#uri_escape(input) ⇒ String

URI escape a string.

Examples:

uri_escape('foo, bar \\baz?')
# => "foo,%20bar%20%5Cbaz?"

Parameters:

  • input (String)

Returns:

  • (String)


86
87
88
# File 'lib/bridgetown-core/filters.rb', line 86

def uri_escape(input)
  Addressable::URI.normalize_component(input)
end

#where(input, property, value) ⇒ Array

Filter an array of objects or a hash (will use values)

Parameters:

  • input (Array, Hash)
  • property (String)

    the property within each object to filter by

  • value (String)

    value for the search

Returns:

  • (Array)

    filtered array of objects



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/bridgetown-core/filters.rb', line 167

def where(input, property, value) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  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 retrive 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

#where_exp(input, variable, expression) ⇒ Array

Filters an array of objects against an expression

Parameters:

  • input (Array, Hash)
  • variable (String)

    the variable to assign each item to in the expression

  • expression (String)

    a Liquid comparison expression passed in as a string

Returns:

  • (Array)

    filtered array of objects



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/bridgetown-core/filters.rb', line 192

def where_exp(input, variable, expression)
  return input unless input.respond_to?(:select)

  input = input.values if input.is_a?(Hash)

  condition = parse_condition(expression)
  @context.stack do
    input.select do |object|
      @context[variable] = object
      condition.evaluate(@context)
    end
  end || []
end

#xml_escape(input) ⇒ String

XML escape a string for use. Replaces any special characters with appropriate HTML entity replacements.

Examples:

xml_escape('foo "bar" <baz>')
# => "foo &quot;bar&quot; &lt;baz&gt;"

Parameters:

  • input (String)

Returns:

  • (String)


61
62
63
# File 'lib/bridgetown-core/filters.rb', line 61

def xml_escape(input)
  Utils.xml_escape(input)
end