Showing posts with label format. Show all posts
Showing posts with label format. Show all posts

Tuesday, March 3, 2009

Change Default Date Format in Ruby on Rails

Just a quick and simple hint!

If you need to set the default formatting of dates throughout your whole application in Ruby on Rails, just add the following line to your "<your application>/config/environment.rb"

my_date_formats = { :default => '%d/%m/%Y' }

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(my_date_formats)

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(my_date_formats)


Note 1: Rails uses this :default format when attempting to write dates do the database, so be sure that your DBMS is able to use this new format

Note 2: you will need to restart your server so the changes will be effective.

Find this article also on Define Null.

Tuesday, February 10, 2009

Format Currency in Ruby on Rails

I was looking for a way to display currency data coming from the database as a long. I found out that Ruby on Rails has a buil-in Module Helper method called
ActionView::Helpers::NumberHelper:number_to_currency which allows one to format a number according to some options:


  • :precision - Sets the level of precision (defaults to 2).

  • :unit - Sets the denomination of the currency (defaults to "$").

  • :separator - Sets the separator between the units (defaults to ".").

  • :delimiter - Sets the thousands delimiter (defaults to ",").

  • :format - Sets the format of the output string (defaults to "%u%n").


Using this method, we could write something like this:


<%=h number_to_currency @transaction.value, :unit => 'R$', :separator => ",", :delimiter => "." %>

This would work fine, but in this solution we are breaking the DRY (Don't Repeat Yourself) rule, because I would need to set the same parameters in every place I was displaying currency values.

A better solution would be to have a helper method which I could use in every piece of code where I need a currency. So I came up with the solution below, which consists in writing my own helper method in app/helpers/application_helper.rb:

module ApplicationHelper

number_to_currency(number,:delimiter => ".", :unit => "R$ ",:separator => ",")
end
end

Now, in my templates I should write something like this:

<%=h real_currency @transaction.value %>


Ain't that easier?


Find this article also on Define Null.