Created
April 2, 2014 02:25
-
-
Save kristianfreeman/9926970 to your computer and use it in GitHub Desktop.
easy currency in rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(note you could probably get away with not using
require 'money'
if you have autoloading set up)