Topic: How to use Rails Time or Date classes in a Ruby file

I can't figure out why Time/Date classes methods from activesupport are not recognized in a separate Ruby file that I would like to execute in a not Rails application. Strange because activerecord methods work fine.
So here is some piece of code that I tried to execute from a terminal just as a simple Ruby file:

require 'rubygems'
require 'active_support'

t = Time.now
puts t.beginning_of_month

Here is the error:

C:\...\lib>ruby rails_dates.rb
rails_dates.rb:5:in `<main>': undefined method `beginning_of_month' for 2011-06-29 11:16:31 +0200:Time (NoMethodError)

I tested it on Windows XP OS, Ruby 1.9.2, rails 3.0.9
Any idea? Thanks a lot

Last edited by Javix (2011-06-29 05:19:29)

Re: How to use Rails Time or Date classes in a Ruby file

Hi, try out this piece of code

require 'active_support/all'

t = Time.now
puts t.beginning_of_month

by the way, if you use ruby 1.9, you can omit

require 'rubygems'

Re: How to use Rails Time or Date classes in a Ruby file

Yep ! It worked, thanks a lot !

Re: How to use Rails Time or Date classes in a Ruby file

But if you use 'active_support/all', you'll load all core extensions. For loading only 'beginning_of_month' definition you can use this:

require 'active_support/core_ext/time/calculations'

Re: How to use Rails Time or Date classes in a Ruby file

ok, thank you!