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

Suggestions on formatting JSON serialization? #86

Open
chrismanderson opened this issue Sep 15, 2021 · 4 comments
Open

Suggestions on formatting JSON serialization? #86

chrismanderson opened this issue Sep 15, 2021 · 4 comments

Comments

@chrismanderson
Copy link

Hello! Experimenting with the gem with a basic rails api - any suggestions on a good entry point/mechanism for customizing the JSON output of a ActiveRecord attribute storing a Tod::TimeOfDay? I'd like to show the outpost as a '11:00:00' for example rather than the components.

I'm just using a simple as_json for my models. There's lots of ways of doing this of course, adding a method that does the string formatting, using ActiveModelSerializers and overriding the attribute getter, but I'd like to find a higher-level way of customizing the output, if possible. Thank you!

@jackc
Copy link
Owner

jackc commented Sep 18, 2021

I'm not exactly sure what your asking for, but I'm open to adding as_json to Tod::TimeOfDay. That might do what you want.

@chrismanderson
Copy link
Author

That's pretty much what I'm looking for!

Should have clarified more, but say I have a class

class Reservation < ActiveRecord::Base
  attribute :name, :string
  attribute :time, :time_only
end

Outputting this class to JSON (without any custom serialization) would give me

{
  'name': 'My reservation',
  'time': {
    'hour': 11,
    'minute': 0,
    'second': 0,
    'second_of_day': 39600
  }
}

But I'd love to able to output something like

{
  'name': 'My reservation',
  'time': '11:00:00'
}

And, there are ways to do this with custom serializers and such for sure, but was looking for a way to avoid that, as I tend to output my Rails JSON objects without heavy serializers.

@jackc
Copy link
Owner

jackc commented Sep 18, 2021

I haven't looked into internals of ActiveRecord lately but I presume the all that would be necessary adding this method to Tod::TimeOfDay:

def as_json; to_s; end

Maybe you could try monkey patching to see if that does what you want. If it does, I could merge a PR with that method.

@dush
Copy link

dush commented May 19, 2022

It works as expected

# Fix JSON serialization of Tod::TimeOfDay
module TimeOfDayAsJson
  def as_json(*)
    to_s
  end
end

Tod::TimeOfDay.include TimeOfDayAsJson
Tod::TimeOfDay("12:23:45").as_json
=> "12:23:45"

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

No branches or pull requests

3 participants