开发者

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 fo开发者_JS百科rmat 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!


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜