`
cvu
  • 浏览: 104811 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

amount_in_yuan

阅读更多
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 %>元
...
分享到:
评论
2 楼 cvu 2007-01-24  
看到了,谢谢!
add_column :products, :price, :decimal, :precision => 8, :scale => 2
1 楼 gigix 2007-01-24  
看那本书第二版。现在提倡的做法是用一个BigDecimal字段来保存价格。

相关推荐

Global site tag (gtag.js) - Google Analytics