Module: ToFilter

Defined in:
lib/liquidum/liquid/filters/to_filter.rb

Instance Method Summary collapse

Instance Method Details

#to(input, format, options = {}) ⇒ Object

Turn object in something else

Example:

{{message.payload | to: 'json'}}
{{message.payload | to: 'yaml'}}

Advanced example:

{{payload | to: 'json', pretty: true}}
{%assign today = 'now'|to: 'date'%}


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
# File 'lib/liquidum/liquid/filters/to_filter.rb', line 14

def to(input, format, options = {})
  case format
  when 'yaml'
    to_dump = input
    to_dump = to_dump.to_h if input.is_a?(HashWithIndifferentAccess)
    result  = YAML.dump(to_dump)
    result  = result.gsub(/^---\n/, '') if options['inline']
    result
  when 'json'
    if options['pretty']
      JSON.pretty_generate(input)
    else
      input.to_json
    end
  when 'date'
    date = Liquid::Utils.to_date(input)

    return input if date.to_s.empty?
    return date if options[:format].to_s.empty?

    date.strftime(options[:format].to_s)
  when 'sgid'
    return '' if input.nil? || !input.respond_to?(:to_sgid)

    # Should accept for and expires_on options but vorto/nuntius does not allow that
    input.to_sgid.to_s
  else
    raise 'No to format given'
  end
end