Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RABL: change default date and time format to iso8601

I'm using rabl 0.11.6 for my API, and I find myself doing the following over and over again for every date or time object:

node :created_at do |article|
  article.created_at.iso8601
end

It would save a lot of code duplication, if the format for every date object could be set in one place, so that I just could use the attributes method like this

attributes :created_at

I found an issue on github (https://github.com/ccocchi/rabl-rails/issues/68) where they suggest, overwriting some Oj.default_options = { mode: :compat, time_format: :ruby } in an initializer. But I have no idea how to do a .iso8601.

Then I found this one https://gist.github.com/astevens/b80225d96d8889c946ac. But it looks like a hacky monkey patch solution.

And finally I found this issue https://github.com/nesquena/rabl/issues/336 where they overwrite the as_json method from ActiveSupport::TimeWithZone, also a very monkey-patch solution.

Is there no way to tell RABL what date and time format to use? And if not, what would be the best / least-hacky method to achieve this?

like image 792
23tux Avatar asked Oct 19 '22 03:10

23tux


1 Answers

FWIW I fixed this problem in rails 4.2.8, Rabl 0.13.1 and OJ 2.18.5

Add a initializer with the following..

Oj.default_options = {:use_as_json => true}
like image 123
Gordon Avatar answered Nov 03 '22 06:11

Gordon