Skip to content

Instantly share code, notes, and snippets.

@kristianfreeman
Created April 2, 2014 02:25
Show Gist options
  • Save kristianfreeman/9926970 to your computer and use it in GitHub Desktop.
Save kristianfreeman/9926970 to your computer and use it in GitHub Desktop.
easy currency in rails
product = Product.new price_cents: 5000
product.price_string # => "$50.00"
product = Product.new price_cents: 51254
product.price_string # => "$512.54"
product = Product.new price_cents: 512
product.price_string # => "$5.12"
module Money
def currency
@_currency ||= "$"
end
def currency_position
@_position ||= :before
end
def formatted_money(float)
string = '%.2f' % float
if currency_position == :after
string + currency
else
currency + string
end
end
end
require 'money'
class Product < ActiveRecord::Base
include Money
belongs_to :user
def price
price_cents * 0.01
end
def price_string
formatted_money(price)
end
end
@kristianfreeman
Copy link
Author

(note you could probably get away with not using require 'money' if you have autoloading set up)

@kristianfreeman
Copy link
Author

this could probably be money.rb but i'm way too lazy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment