Created
December 3, 2010 20:20
-
-
Save lancejpollard/727494 to your computer and use it in GitHub Desktop.
Format attributes when they are set in ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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