views:

349

answers:

1

I write my first project wich using Datamapper as ORM, so please be patient. :)

I try to do get String from DateTime field:

Error.first.submitted_at.to_s => "2009-08-24T12:13:32+02:00"

Returned String is not good for me. In ActiveRecord I can do something like that:

Error.first.submitted_at.to_s(:only_date)

or any other date formatter. Is somethig similar available in DataMapper or I must to use strftime method?

+1  A: 

That's a feature available using AcitveSupport. You can do require 'activesupport' to get it. That might be overkill, though. You could also use #stamp from Facets to do the same thing, but you have to set up the :only_date format:

require 'facets/date'

Date::FORMAT[:only_date] = '%d.%m.%y'  # For Date objects
Time::FORMAT[:only_date] = '%d.%m.%y'  # For DateTime objects

d = DateTime.now
d.stamp(:only_date)  # => "24.08.09"

If you really want to use it with the to_s method, you can do that, too:

require 'facets/date'

Date::FORMAT[:only_date] = '%d.%m.%y'  # For Date objects
Time::FORMAT[:only_date] = '%d.%m.%y'  # For DateTime objects

class DateTime
  alias :default_to_s :to_s
  def to_s(format=nil)
    if format.nil?
      default_to_s
    else
      stamp format
    end
  end
end

d = DateTime.now
d.to_s(:only_date)  # => "24.08.09"
Pesto
Well, I have hope that DataMapper supports it somehow. I will extend DateTime class with my implementation to_s. Thanks.
Sebastian