Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Last active September 6, 2022 02:20
Show Gist options
  • Select an option

  • Save dpaluy/9f71cf20d93bc17dd6222eff42cb4ccf to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/9f71cf20d93bc17dd6222eff42cb4ccf to your computer and use it in GitHub Desktop.
a custom type that defines a cast method which will branch on the not-completely-bulletproof heuristic of assuming Numeric values are already in cents and any other values will need to be converted from dollars.
class Cents < ActiveRecord::Type::Integer
def cast(value)
return super if value.is_a?(Numeric)
price_in_dollars = value.to_s.delete("$").to_d
price_in_cents = (price_in_dollars * 100).to_i
super(price_in_cents)
end
def self.dollarize(value)
price_in_cents = value.to_d
"$#{"%.2f" % (price_in_cents / 100)}"
end
end
# Globally register:
ActiveModel::Type.register(:cents, Cents)
# usage:
attribute :max_price, :cents, default: -> { 100_00 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment