Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A simple acts_as style plugin for easily formatting of dates within Rails models
Ruby
Branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
CHANGELOG
MIT-LICENSE
README.textile
Rakefile
VERSION
formatted-dates.gemspec
init.rb

README.textile

FormattedDates

I flippin’ hate mucking about with strftime everytime I want to format dates. I hate adding new methods messing up my models. I hate .to_formatted_string.

This formatted_dates plugin is a quick acts_as hook into strftime for date fields your Rails models.

Installation

Add this to config/environment.rb :

config.gem 'formatted-dates', :lib => 'formatted_dates', :version => '0.0.1', :source => 'http://gemcutter.org'

and run:

sudo rake gems:install

or

./script/plugin install git://github.com/paulca/formatted-dates.git

Example

In yer model:

Account < ActiveRecord::Base
  format_dates :timestamps
end

This will give you access to new methods with formatted appended to the end of any standard Rails timestamps in your model (eg. created_at, updated_at, created_on, updatedon):

They format using the default of “%e %B, %Y”, which gives something like this:
updated_on_formatted => “9 April, 2003”

You can provide your own string to pass to strftime:

Account < ActiveRecord::Base
  format_dates :timestamps, :format => "%m/%d/%Y"
end

And you can pass in other date fields from your model to be formatted:

Account < ActiveRecord::Base
  format_dates [:timestamps, :registered_on, :last_login_date], :format => "%m/%d/%Y"
end

You can also format multiple fields differently:

Account < ActiveRecord::Base
  format_dates :timestamps
  format_dates :registered_on, :format => "%I:%M%p"
  format_dates :last_login_date, :format => "%m/%d/%Y"
end

If you want to display the time for ‘today’ differently you can do so:

Account < ActiveRecord::Base
  format_dates :created_on, :today => "%l:%M%p"
end<code></pre>

And if you want to filter the resulting string, you can do so too:

If you want to display the time for ‘today’ differently you can do so:

Account < ActiveRecord::Base
  format_dates :created_on, :today => "%l:%M%p", :filter => :downcase # => '10:10pm'
emd

Finally, you can alias your formatted dates to a nice short, memorable name:

Account < ActiveRecord::Base
  format_dates :created_on, :as => :date
end

This gives you a method @account.date that is equivalent to created_on_formatted

Copyright © 2008, 2009 Paul Campbell, released under the MIT license.

Follow me on Twitter: http://www.twitter.com/paulca

More ramblings on http://www.pabcas.com

Something went wrong with that request. Please try again.