Skip to content

@lancejpollard /format_attributes.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.