Module: MoneyAttribute::FormBuilderExtension

Defined in:
lib/money_attribute/form_builder_extension.rb

Overview

Form builder methods for money attributes.

Included into ActionView::Helpers::FormBuilder by the railtie, providing two helper methods that mirror Rails' text_field and number_field but work with Mint::Money attribute values.

Both helpers render unbound <input> tags (not scoped to the form builder's object name), so the submitted value is accessible via params directly rather than through params[object_name].

Examples:

In a view

<%= form_with model: @product do |f| %>
  <%= f.money_field :price %>
  <%= f.money_amount_field :discount %>
<% end %>

Instance Method Summary collapse

Instance Method Details

#money_amount_field(method, options = {}) ⇒ String

Renders a number input for a single-column (fixed-currency) money attribute.

Displays the raw decimal value (e.g. "1234.56") via Mint::Money#to_d. This is suitable for attributes backed by a single column where the currency is fixed per application config.

Examples:

f.money_amount_field :discount
# => <input type="number" id="product_discount" name="product_discount" value="1234.56">

With step and min

f.money_amount_field :discount, step: 0.01, min: 0

Parameters:

  • method (Symbol)

    the money attribute accessor name

  • options (Hash) (defaults to: {})

    HTML attributes passed through to the input tag

Returns:

  • (String)

    an HTML <input type="number"> tag



61
62
63
64
65
66
67
# File 'lib/money_attribute/form_builder_extension.rb', line 61

def money_amount_field(method, options = {})
  money_from_column = object.public_send(method)
  value = money_from_column&.to_d

  @template.number_field_tag(field_name(method), value,
                             { id: field_id(method) }.merge(options))
end

#money_field(method, options = {}) ⇒ String

Renders a text input for a composed (amount + currency) money attribute.

Displays the formatted money string (e.g. "R$ 1.234,56") via Mint::Money#to_fs. The raw value is submitted as a string; the application should parse it on the receiving end, typically using Converter#parse.

Examples:

f.money_field :price
# => <input type="text" id="product_price" name="product_price" value="R$ 1.234,56">

With CSS class

f.money_field :price, class: "form-control"

Parameters:

  • method (Symbol)

    the money attribute accessor name

  • options (Hash) (defaults to: {})

    HTML attributes passed through to the input tag

Returns:

  • (String)

    an HTML <input type="text"> tag



37
38
39
40
41
42
43
# File 'lib/money_attribute/form_builder_extension.rb', line 37

def money_field(method, options = {})
  money = object.public_send(method)
  value = money&.to_fs

  @template.text_field_tag(field_name(method), value,
                           { id: field_id(method) }.merge(options))
end