Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created June 30, 2009 16:50
Show Gist options
  • Save joshuaclayton/138265 to your computer and use it in GitHub Desktop.
Save joshuaclayton/138265 to your computer and use it in GitHub Desktop.
module PercentBase
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def has_percent(attribute_name = :pretty_percent, column = :percent)
raise(ArgumentError, "Cannot name attribute and column the same") if attribute_name.to_s == column.to_s
class_eval <<-END
def #{attribute_name}=(value)
return if value == ''
self[:#{column}] = value.nil? ? nil : (value.to_s.gsub(/[^\\d\\.]/, '').to_f)/100
end
def #{attribute_name}
return nil if self[:#{column}].blank?
perc = self[:#{column}] * 100
perc = perc.to_i == perc ? perc.to_i : perc
perc.to_s + "%"
end
END
end
end
end
ActiveRecord::Base.send :include, PercentBase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment