Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created December 3, 2010 20:20
Show Gist options
  • Save lancejpollard/727494 to your computer and use it in GitHub Desktop.
Save lancejpollard/727494 to your computer and use it in GitHub Desktop.
Format attributes when they are set in ActiveRecord
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment