Skip to content

Instantly share code, notes, and snippets.

@skojin
Created March 9, 2010 17:06
Show Gist options
  • Save skojin/326824 to your computer and use it in GitHub Desktop.
Save skojin/326824 to your computer and use it in GitHub Desktop.
virtual formatted date attribute
# inspired by http://railsforum.com/viewtopic.php?pid=6676#p6676
module FormattedDateAttribute
# define virtual formatted date attribute
# formatted_date_attribute(:start_on, :formatted_start_on, :us_format)
# formatted_date_attribute(:start_on, :formatted_start_on, "%m/%d/%Y")
def formatted_date_attribute(attr_name, formatted_name, format)
define_method(formatted_name) do
return self[attr_name] unless self[attr_name]
format.is_a?(Symbol) ? self[attr_name].to_s(format) : self[attr_name].strftime(format)
end
define_method("#{formatted_name}=") do |value|
self[attr_name] = value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment