Module: AmountField::Helpers::FormBuilder

Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/amount_field/form_helper.rb

Instance Method Summary collapse

Instance Method Details

#amount_field(method, options = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/amount_field/form_helper.rb', line 39

def amount_field(method, options = {})
  format_options = I18n.t(:'number.amount_field.format', :raise => true) rescue {}
  format_options = format_options.merge(AmountField::ActiveRecord::Validations.configuration)
  format_options.merge!(options.delete(:format) || {})

  if (explicit_object = options.delete(:object))
    self.object = explicit_object
  end

  # if no explicit value is given, we set a formatted one. In case of an error we take the
  # original value inserted by the user.
  if object.errors[method].blank?
    options[:value] ||= number_with_precision(object.send(method), format_options)
  else
    options[:value] ||= object.send("#{AmountField::Configuration.prefix}_#{method}") || object.send("#{method}_before_type_cast")
  end

  # Note: we don't set options[:id] here, because caller or Rails knows best what to do.
  # We accidentally set it to "foo[bar]_name" instead of "foo_bar_name".
  options[:name]  ||= "#{object_name}[#{AmountField::Configuration.prefix}_#{method}]"
  options[:class] = "#{options[:class]} #{AmountField::Configuration.css_class}"
  
  text_field(method, options)
end