Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Todd Sayre http://del.icio.us/sporkyy

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Number to Currency with Cents

A slight alteration to the default Rails currency formatting helper to show numbers in cents if the number is less than $1.00. For example $0.99 would instead become 99¢.

def number_to_currency_with_cents(number, options = {})
    options = options.stringify_keys
    precision = options.delete('precision') { 2 }
    unit = options.delete('unit') { '$' }
    fractional_unit = options.delete('fractional_unit') { '¢' }
    separator = options.delete('separator') { '.' }
    delimiter = options.delete('delimiter') { ',' }
    separator = '' unless precision > 0
    begin
        fraction = number.abs % 1.0
        body = number.floor
        if body != 0 || body == 0 && fraction == 0 then
            parts = number_with_precision(number, precision).split('.')
            unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s
        else
            (fraction * 100).to_i.to_s + fractional_unit
        end
    rescue
        number
    end
end


I'm really tempted to go through and replace that whole thing with my own code, but it works, so I'm happy.

Gmail Date Format Helper

I needed a short and intuitive way of showing dates, so rather than just making something up I decided to steal Google's short date format from Gmail. I'm sure they did usability studies and whatnot.

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)


Put this code in your "environmen.rb" file in your "RAILS_ROOT/config" directory or make a new Ruby script file containing it in your "RAILS_ROOT/config/initializers" directory.
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS