我在我的 Rails 应用程序中使用一个模块来执行一些操作并呈现一个 html 文件并将其保存到 S3。到目前为止一切顺利,除了我需要传递一个要呈现的货币变量并且 erb 抛出这个错误:
undefined method `/' for "3,395,000":String
这是我的代码:
options = {
...
price: Money.new(@case.cash_price / 100.to_i, "DKK").format.to_s.html_safe,
...
}
这是我的模块:
def generate_html(options)
require 'erb'
erb_file = "templates/banners/widesky.html.erb"
erb_str = File.read(erb_file)
...
@price = options[:price]
...
renderer = ERB.new(erb_str)
result = renderer.result(binding)
FileUtils.mkdir_p('temp') unless File.directory?('temp')
File.open('temp/index.html', 'w') do |f|
f.write(result)
end
'temp/index.html'
end
我尝试用不同的方式格式化货币,但我总是得到同样的错误。有什么想法吗?
编辑
@case.cash_price
原本是一个整数。我想将其转换为带逗号的字符串(因此使用 Money 对其进行格式化)。问题似乎是 erb
不喜欢格式化的结果并抛出上述错误。
最佳答案
如果由于某种原因您不能使用任何 gem/helper,让我们重新发明轮子!
def to_currency(price_in_cents, currency=nil, decimal_separator = '.', thousand_separator = ',')
price_in_cents.to_s.rjust(3,'0').reverse.insert(2,decimal_separator).gsub(/(\d{3})(?=\d)/, '\1'+thousand_separator).reverse+(currency ? " #{currency}" : '')
end
puts to_currency(123456789, 'DKK')
puts to_currency(123456, '€', ',', ' ')
puts to_currency(1)
输出:
1,234,567.89 DKK
1 234,56 €
0.01
请注意,price_in_cents 应该是看起来像整数(“123456789”)或整数(123456789)的字符串,而不是预格式化的字符串(“123,456.78”)或 float (1.23)。 最后,生成的字符串与 price_in_cents 一样不安全:
to_currency("unsafe_codejs")
=> "unsafe_code.js"
无论如何,您不必在结果上指定 html_safe,因为“1,234,567.89 DKK”中的任何内容都不会被转义。
原始答案:
如果cash_price是带逗号的String,需要先去掉逗号,然后转成float,再除以100,再转成Integer。 cash_price.to_s 是为了避免在 cash_price 以数字形式出现时出现错误。
price: Money.new((@case.cash_price.to_s.delete(',').to_f/100).to_i, "DKK").format.to_s.html_safe
关于ruby-on-rails - 如何解决传递货币格式字符串时 erb 抛出的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333221/