Skip to content

Instantly share code, notes, and snippets.

@oddlyzen
Created February 14, 2010 10:44
Show Gist options
  • Save oddlyzen/303949 to your computer and use it in GitHub Desktop.
Save oddlyzen/303949 to your computer and use it in GitHub Desktop.
class HoboType::Cents < DelegateClass(Fixnum)
COLUMN_TYPE = :integer
HoboFields.register_type(:cents, self)
def initialize(value)
super(centsify value)
end
def to_s
sprintf("%.2f", self.to_f / 100)
end
def to_microformat
'<span class="money">' +
'<abbr class="currency" title="USD">$</abbr>' +
'<span class="amount">' + to_s + '</span>' +
'</span>'
end
def to_rdfa
'<span property="commerce:currency" content="USD">$</span>' +
'<span property="commerce:amount" datatype="xsd:decimal">' + to_s + '</span>'
end
def to_html(xmldoctype = true)
to_microformat
end
private
def centsify(value)
case value
when String
# string to cents stolen from the money gem
value.insert(0,'0') if value =~ /^\./
matches = value.scan /(\-?[\d,]+(\.(\d+))?)/
matches[0] ? (matches[0][0].gsub(',', '').to_f * 100).round : 0
when Float
(value * 100).round
when Fixnum
value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment