# config/initializers/active_record/money_type.rb classMoneyType < ActiveRecord::Type::Integer defcast(value) if !value.kind_of?(Numeric) && value.include?('$') price_in_dollars = value.gsub(/\$/, '').to_f super(price_in_dollars * 100) else super end end end
ActiveRecord::Type.register(:money, MoneyType)
# /app/models/store_listing.rb classStoreListing < ActiveRecord::Base attribute :price_in_cents, :money end
# config/initializers/active_record/money_type.rb classOriginalJson definitialize(hash) @json = hash.try(:symbolize_keys) end
defhoge @json['hoge'] end defto_h @json end
# For casting classType < ActiveRecord::Type::Value # 型を書く deftype end
# DBから値を取り出す時のキャスト処理 defdeserialize(value) cast(value) end
# ユーザー入力をキャストする処理 defcast(value) if String === value decoded = ::ActiveSupport::JSON.decode(value) rescuenil ::OriginalJson.new(decoded) else super end end
# DBの保存のために、DBが認識できる型に変換 # +String+, +Numeric+, +Date+, +Time+, +Symbol+, +true+, +false+, +nil+ defserialize(value) case value when Hash ::ActiveSupport::JSON.encode(value) when::OriginalJson ::ActiveSupport::JSON.encode(value.to_h) else super end end end end
# Adding OriginalJson::Type to ActiveRecord::Type ActiveRecord::Type.register(:original_json, OriginalJson::Type)