Module: Dugway::Filters::UtilFilters

Defined in:
lib/dugway/liquid/filters/util_filters.rb

Constant Summary collapse

DEFAULT_CURRENCY_VALUES =
{ :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",", :precision => 2, :significant => false, :strip_insignificant_zeros => false }

Instance Method Summary collapse

Instance Method Details

#content_tag(type, content, options = {}) ⇒ Object



118
119
120
121
122
# File 'lib/dugway/liquid/filters/util_filters.rb', line 118

def (type, content, options = {})
  result  = tag(type, options, true)
  result += content.to_s
  result += "</#{type}>"
end

#hidden_field_tag(name, value = nil, options = {}) ⇒ Object



136
137
138
# File 'lib/dugway/liquid/filters/util_filters.rb', line 136

def hidden_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.stringify_keys.update("type" => "hidden"))
end

#number_to_currency(number, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/dugway/liquid/filters/util_filters.rb', line 7

def number_to_currency(number, options={})
  return unless number

  options.symbolize_keys!

  defaults  = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  currency  = I18n.translate(:'number.currency.format', :locale => options[:locale], :default => {})
  currency[:negative_format] ||= "-" + currency[:format] if currency[:format]

  defaults  = DEFAULT_CURRENCY_VALUES.merge(defaults).merge!(currency)
  defaults[:negative_format] = "-" + options[:format] if options[:format]
  options   = defaults.merge!(options)

  unit      = options.delete(:unit)
  format    = options.delete(:format)

  if number.to_f < 0
    format = options.delete(:negative_format)
    number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
  end

  value = number_with_precision(number, options)
  format.gsub(/%n/, value).gsub(/%u/, unit)
end

#number_with_delimiter(number, options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/dugway/liquid/filters/util_filters.rb', line 32

def number_with_delimiter(number, options={})
  options.symbolize_keys!

  begin
    Float(number)
  rescue ArgumentError, TypeError
    if options[:raise]
      raise InvalidNumberError, number
    else
      return number
    end
  end

  defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  options = options.reverse_merge(defaults)

  parts = number.to_s.to_str.split('.')
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
  parts.join(options[:separator]).html_safe
end

#number_with_precision(number, options = {}) ⇒ Object



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
# File 'lib/dugway/liquid/filters/util_filters.rb', line 53

def number_with_precision(number, options={})
  options.symbolize_keys!

  number = begin
    Float(number)
  rescue ArgumentError, TypeError
    if options[:raise]
      raise InvalidNumberError, number
    else
      return number
    end
  end

  defaults           = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
  precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale], :default => {})
  defaults           = defaults.merge(precision_defaults)

  options = options.reverse_merge(defaults)  # Allow the user to unset default values: Eg.: :significant => false
  precision = options.delete :precision
  significant = options.delete :significant
  strip_insignificant_zeros = options.delete :strip_insignificant_zeros

  if significant and precision > 0
    if number == 0
      digits, rounded_number = 1, 0
    else
      digits = (Math.log10(number.abs) + 1).floor
      rounded_number = (BigDecimal(number.to_s) / BigDecimal((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
      digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
    end
    precision -= digits
    precision = precision > 0 ? precision : 0  #don't let it be negative
  else
    rounded_number = BigDecimal(number.to_s).round(precision).to_f
  end
  formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
  if strip_insignificant_zeros
    escaped_separator = Regexp.escape(options[:separator])
    formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '').html_safe
  else
    formatted_number
  end
end

#option_tag(name, value, selected = false) ⇒ Object



128
129
130
# File 'lib/dugway/liquid/filters/util_filters.rb', line 128

def option_tag(name, value, selected=false)
   :option, name, { :value => value, :selected => selected ? 'selected' : nil }
end

#radio_button_tag(name, value, checked = false, options = {}) ⇒ Object



150
151
152
153
154
155
156
# File 'lib/dugway/liquid/filters/util_filters.rb', line 150

def radio_button_tag(name, value, checked = false, options = {})
  pretty_tag_value = value.to_s.gsub(/\s/, "_").gsub(/(?!-)\W/, "").downcase
  pretty_name = name.to_s.gsub(/\[/, "_").gsub(/\]/, "")
  html_options = { "type" => "radio", "name" => name, "id" => "#{pretty_name}_#{pretty_tag_value}", "value" => value }.update(options.stringify_keys)
  html_options["checked"] = "checked" if checked
  tag :input, html_options
end

#select_tag(name, option_tags = nil, options = {}) ⇒ Object



124
125
126
# File 'lib/dugway/liquid/filters/util_filters.rb', line 124

def select_tag(name, option_tags = nil, options = {})
   :select, option_tags, { "name" => name, "id" => name }.update(options.stringify_keys)
end

#tag(name, options = nil, open = false, escape = true) ⇒ Object



97
98
99
# File 'lib/dugway/liquid/filters/util_filters.rb', line 97

def tag(name, options = nil, open = false, escape = true)
  "<#{name}#{tag_options(options, escape) if options}" + (open ? ">" : " />")
end

#tag_options(options, escape = true) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/dugway/liquid/filters/util_filters.rb', line 101

def tag_options(options, escape = true)
  unless options.blank?
    attrs = []
    if escape
      options.each do |key, value|
        next unless value
        key = h(key.to_s)
        value = h(value)
        attrs << %(#{key}="#{value}")
      end
    else
      attrs = options.map { |key, value| %(#{key}="#{value}") }
    end
    " #{attrs.sort * ' '}" unless attrs.empty?
  end
end

#text_area_tag(name, content = nil, options = {}) ⇒ Object



140
141
142
143
144
145
146
147
148
# File 'lib/dugway/liquid/filters/util_filters.rb', line 140

def text_area_tag(name, content = nil, options = {})
  options.stringify_keys!

  if size = options.delete("size")
    options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
  end

   :textarea, content, { "name" => name, "id" => name }.update(options)
end

#text_field_tag(name, value = nil, options = {}) ⇒ Object



132
133
134
# File 'lib/dugway/liquid/filters/util_filters.rb', line 132

def text_field_tag(name, value = nil, options = {})
  tag(:input, { "type" => "text", "name" => name, "id" => name, "value" => value }.update(options.stringify_keys))
end