public
Last active

Format attributes when they are set in ActiveRecord

  • Download Gist
format_attributes.rb
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
module FormatAttribute
unloadable
def self.included(base)
base.class_eval do
class << self
# format :cash, :except => "$"
# format :date do |value|
# Date.parse(value)
# end
def format(attr_name, options = {}, &block)
formats[attr_name.to_sym] = [options, block]
end
 
def formats
@formats ||= {}
end
end
def write_attribute_with_formatting(attr_name, value)
write_attribute_without_formatting(attr_name, formatted_value(attr_name, value))
end
def formatted_value(attr_name, value)
format = self.class.formats[attr_name.to_sym]
if format.present? && value.present?
options = format[0]
block = format[1]
value = value.to_s.gsub(options[:except], "") if options[:except].present?
value = block.call(value) if block.present?
value = self.class.columns_hash[attr_name.to_s].type_cast(value)
value
else
value
end
end
alias_method_chain :write_attribute, :formatting
end
end
end
 
ActiveRecord::Base.send(:include, FormatAttribute)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.