Revisions

gist: 138265 Download_button fork
public
Public Clone URL: git://gist.github.com/138265.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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