Tyrael Tong
Tyrael Tong

Reputation: 761

How to change datetime in xml response using Rails3?

I'm using Rails 3.0.4, Ruby 1.9.2p0 on a Mac machine. While using Sqlite as the default database and successfully added respond_to :xml functionality, I see the datetime format in the xml is something like:

<updated-at type="datetime">2011-03-20T12:15:47Z</updated-at>

While there're several posts on the web (also here) asking how to change the date/time format like using configuration in config/locale/en.yml, or add

Time::DATE_FORMATS[:default] = "%Y-%m-%d %H:%M:%S"

in the initializer file, neither work.

I think the problem is because when I call someobj.to_xml, for the datetime objects, rails will call

datetime.xmlschema

instead of calling

datetime.to_s

which bypass the settings mentioned above. Although I know this may be the culprit, I don't know how to fix it. Anyone has experience on this? Thanks a lot!

Upvotes: 3

Views: 785

Answers (2)

Shtirlic
Shtirlic

Reputation: 692

I put this code into time_formats.rb in initializers to get milliseconds

class ActiveSupport::TimeWithZone
  alias_method :original_xmlschema , :xmlschema
  def xmlschema(fraction_digits = 3)
    original_xmlschema(fraction_digits)
  end
end

Gist on GitHub

Upvotes: 1

tommasop
tommasop

Reputation: 18765

If you absolutely need to change it you can override the xmlschema method instead of the to_s

class DateTime
  def xmlschema
    strftime("%Y-%m-%d %H:%M:%S")
  end
end

But as I said in the comment you are breaking the XLM standard and application connecting to yours will not expect this datetime format.

Upvotes: 1

Related Questions