阅读更多
Agile Web Development On Rails书中建议金额用integer,单位是cents,好处XX。但是每个金额的field都要写两个method:amount_in_dollar和amount_in_dollar=,不如写个类似于attr_accessor的meta program,一次搞定。两段例子如下:
# config/enviorment.rb
class Module
def amounts_in_yuan(*args)
args.each do |sym|
class_eval %{
def #{sym}_in_yuan
amt = self.#{sym} || 0
sprintf("¥%01.2f", amt.to_f/100)
end
def #{sym}_in_yuan=(amt)
amt.sub!('¥', '') if amt.starts_with?('¥')
self.#{sym} = (amt.to_f * 100).to_i
end
}
end
end
end
# db/migrate/001_create_products.rb
class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.column :price, :integer # 金额定义为integer,单位为分
t.column :cost, :integer
...
end
end
...
end
# app/models/product.rb
class Product < ActiveRecord::Base
amounts_in_yuan :price, :cost
...
end
<%# app/views/products/edit.rhtml %>
...
单价:<%= f.text_field :product, :price_in_yuan %>元
成本:<%= f.text_field :product, :cost_in_yuan %>元
...