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") ⇒ Object

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.



152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/bridgetown-core/filters.rb', line 152

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) ⇒ Object

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.



81
82
83
# File 'lib/bridgetown-core/filters.rb', line 81

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.



312
313
314
315
316
# File 'lib/bridgetown-core/filters.rb', line 312

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

  xml_escape(input.inspect)
end

#jsonify(input) ⇒ Object

Convert the input into json string

input - The Array or Hash to be converted

Returns the converted json string



170
171
172
# File 'lib/bridgetown-core/filters.rb', line 170

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

#markdownify(input) ⇒ Object

Convert a Markdown string into HTML output.

input - The Markdown String to convert.

Returns the HTML formatted String.



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

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

#normalize_whitespace(input) ⇒ Object

Replace any whitespace in the input string with a single space

input - The String on which to operate.

Returns the formatted String



119
120
121
# File 'lib/bridgetown-core/filters.rb', line 119

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

#number_of_words(input) ⇒ Object

Count the number of words in the input string.

input - The String on which to operate.

Returns the Integer word count.



128
129
130
# File 'lib/bridgetown-core/filters.rb', line 128

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



104
105
106
107
108
109
110
111
112
# File 'lib/bridgetown-core/filters.rb', line 104

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



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

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



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

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.



135
136
137
138
# File 'lib/bridgetown-core/filters.rb', line 135

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



296
297
298
299
300
301
302
303
304
305
# File 'lib/bridgetown-core/filters.rb', line 296

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



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

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) ⇒ Object

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.



41
42
43
44
# File 'lib/bridgetown-core/filters.rb', line 41

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

#smartify(input) ⇒ Object

Convert quotes into smart quotes.

input - The String to convert.

Returns the smart-quotified String.



30
31
32
# File 'lib/bridgetown-core/filters.rb', line 30

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

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

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

Raises:

  • (ArgumentError)


242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/bridgetown-core/filters.rb', line 242

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) ⇒ Object

Titleize a slug or identifier string.

input - The string to titleize.

Returns a transformed string with spaces and capitalized words. See Utils.titleize_slug for more detail.



52
53
54
# File 'lib/bridgetown-core/filters.rb', line 52

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

#to_integer(input) ⇒ Object

Convert the input into integer

input - the object string

Returns the integer value



228
229
230
231
232
233
# File 'lib/bridgetown-core/filters.rb', line 228

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

  input.to_i
end

#unshift(array, input) ⇒ Object



288
289
290
291
292
293
294
# File 'lib/bridgetown-core/filters.rb', line 288

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) ⇒ Object

URI escape a string.

input - The String to escape.

Examples

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

Returns the escaped String.



95
96
97
# File 'lib/bridgetown-core/filters.rb', line 95

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

#where(input, property, value) ⇒ Object

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



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/bridgetown-core/filters.rb', line 183

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) ⇒ Object

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



209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/bridgetown-core/filters.rb', line 209

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

#xml_escape(input) ⇒ String

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

Examples

xml_escape('foo "bar" ') # => "foo "bar" <baz>"

Parameters:

  • input (String)

    The String to escape.

Returns:

  • (String)

    the escaped String.



66
67
68
# File 'lib/bridgetown-core/filters.rb', line 66

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