---
title: "amount_in_yuan"
author: "cvu"
date: "2007-01-23T23:21:45Z"
tags: ["ActiveRecord", "F#", "Rails", "Ruby", "Web"]
slug: "amount-in-yuan"
draft: false
lastmod: "2007-01-23T23:21:45Z"
id: 49574
url: "https://cvu.iteye.com/blog/49574"
---

*Agile Web Development On Rails*书中建议金额用integer，单位是cents，好处XX。但是每个金额的field都要写两个method：amount_in_dollar和amount_in_dollar=，不如写个类似于attr_accessor的meta program，一次搞定。两段例子如下：


```ruby

# 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

```



```ruby

# 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

```



```ruby

# app/models/product.rb
class Product < ActiveRecord::Base
  amounts_in_yuan :price, :cost
  ...
end

```



```ruby

<%# app/views/products/edit.rhtml %>
...
单价：<%= f.text_field :product, :price_in_yuan %>元
成本：<%= f.text_field :product, :cost_in_yuan %>元
...

```