Reputation: 398
Want to format text in the input field as currency. Found this solution.
So input builder look like this:
def input_group(currency, merged_input_options)
"#{@builder.text_field(attribute_name, merged_input_options)} #{currency_addon(currency)}".html_safe
end
But I still need forcing decimal format of a value:
= f.input :price, as: :currency, input_html: { value: number_with_precision(f.object.price, precision: 2) }
Is it possible to improve builder than it could format number to decimal itself?
Thanks
Upvotes: 0
Views: 1975
Reputation: 1509
Yes it's possible, here is a fully functional example. HTML classes are matching use of Bootstrap 5 style, and Simple Form is configured to use HTML 5 variants.
To use the new input as
f.input :price, as: :currency
Put it in app/lib/simple_form/inputs/currency_input.rb
# frozen_string_literal: true
module SimpleForm
module Inputs
class CurrencyInput < SimpleForm::Inputs::Base
include ActionView::Helpers::NumberHelper
def input(wrapper_options)
currency = options.delete(:currency) || default_currency
wrapper_options = wrapper_options.merge(
value: number_with_precision(@builder.object.send(attribute_name) / 100.0, precision: 2),
type: "number",
step: 1,
lang: "#{I18n.locale}",
)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
content_tag(:div, input_group(currency, merged_input_options), class: "input-group")
end
private
def input_group(currency, merged_input_options)
"#{@builder.text_field(attribute_name, merged_input_options)} #{currency_addon(currency)} ".html_safe
end
def currency_addon(currency)
content_tag(:span, currency, class: "input-group-text")
end
def default_currency
"€"
end
end
end
end
Upvotes: 0
Reputation: 107
You need def input group
to return a float value? If so, have you tried simply to_f
? http://apidock.com/ruby/String/to_f
Upvotes: 0