金額変換方法class Module def attr_as_amount(new...

1477 ワード

db:
class CreateProductions < ActiveRecord::Migration
  def change
    create_table :productions do |t|
      t.string :name
      t.integer :price

      t.timestamps
    end
  end
end

 
lib/models/common.rb
class Module
  def attr_as_amount(new_name, old_name )
    module_eval <<-STR, __FILE__, __LINE__ + 1
      def #{new_name}; sprintf '%0.2f',self.#{old_name}/100; end          # def subject; sprintf '%0.2f',self.title; end
      def #{new_name}?; self.#{old_name}?; end        # def subject?; self.title?; end
      def #{new_name}=(v); self.#{old_name} = v.to_i*100; end  # def subject=(v); self.title = v.to_i*100; end
    STR
  end
end

モジュールに追加:
require "models/common"

class Production < ActiveRecord::Base
  validates_presence_of :name, :price 
  attr_as_amount :price_as_amount,:price
end

注意するのはrails 2.3.5ではrequire"lib/models/common"だがrails 3ではrequire'models/common
次に、
─$ rails c
Loading development environment (Rails 3.2.1)
1.9.3p125 :001 > p = Production.new
 => #<Production id: nil, name: nil, price: nil, created_at: nil, updated_at: nil> 
1.9.3p125 :002 > p.price_as_amount = 1000
 => 1000 
1.9.3p125 :003 >  p.price_as_amount
 => "1000.00" 
1.9.3p125 :004 > p.price
 => 100000 
1.9.3p125 :005 > reload!