Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ptzn/1006828 to your computer and use it in GitHub Desktop.
Save ptzn/1006828 to your computer and use it in GitHub Desktop.
virtual formatted date attribute
module FormattedDateAttributes
# Define virtual formatted date attribute
#
# formatted_date_attribute(:start_at, :end_at, :format => :default)
# formatted_date_attribute(:start_at, :end_at, :format => '%d/%m/%y')
#
# format parameter can be a symbol from config/initializers/date_time_formats.rb or any
# string format that will work with Date#strftime and DateTime.strptime methods
def formatted_date_attributes(*args)
options = { :format => :default }.merge(args.extract_options!)
args.each do |attr_name|
formatted_name = "formatted_#{attr_name}"
define_method(formatted_name) do
return self[attr_name] unless self[attr_name]
options[:format].is_a?(Symbol) ? self[attr_name].to_s(options[:format]) : self[attr_name].strftime(options[:format])
end
define_method("#{formatted_name}=") do |value|
return if value.blank?
format = if options[:format].is_a?(Symbol)
column_for_attribute(attr_name).type == :date ? Date::DATE_FORMATS[options[:format]] : Time::DATE_FORMATS[options[:format]]
else
options[:format]
end
self[attr_name] = DateTime.strptime(value, format)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment