Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can I globaly change the output format types ? #336

Closed
kidpollo opened this issue Sep 26, 2012 · 3 comments
Closed

Can I globaly change the output format types ? #336

kidpollo opened this issue Sep 26, 2012 · 3 comments
Labels

Comments

@kidpollo
Copy link

Hi!

I am getting

"last_activity_at": "2012-08-21T22:29:38Z"

For date time fields. Is there a way to change the output format fro all DateTime attributes? What If I want a format like "2012-08-21 22:29:38 UTC" but for all DateTimes in all my templates.

Could it be done per class type?

Thaks

@nesquena
Copy link
Owner

On dates and times and all that, RABL is just calling to_json on the date or time. In JSON output, the spec recommends http://en.wikipedia.org/wiki/ISO_8601 which is the format being used by default. To change away from that, I would recommend perhaps a helper or a more manual approach using a partial:

# _date.rabl
node @attribute do 
  @date.some_special_format
end

and then:

partial("date.json.rabl", :locals => { :attribute => :created_at, :date => @object.created_at }

Purely aircoded so it may not work exactly, but the gist is there. Also you could overwrite to_json on Time:

class Time
  def to_json
    some_other_format
  end
end

@databyte
Copy link
Collaborator

Closing. If still a question or problem, please reopen.

@knu
Copy link

knu commented Mar 17, 2015

When using oj with rabl, you'd better override as_json instead of to_json, because Oj.dump tries as_json prior to to_json.
For example, the ActiveSupport::TimeWithZone class has as_json defined, so overriding its to_json method does not affect how Oj dumps instances of the class. You need to override as_json instead.

class ActiveSupport::TimeWithZone
  def as_json
    iso8601(6)
  end
end

It took me awhile to find this, so I thought it's worth sharing it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants