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

Is it possible to override the format used when printing a Timestamp? #501

Open
arianf opened this issue Jul 12, 2022 · 0 comments
Open

Comments

@arianf
Copy link

arianf commented Jul 12, 2022

Is it possible to override the format used when doing JSON.pretty_generate for timestamps?

I've tried creating a refinement, but it's not working as expected.

module ActiveSupportExtensions
  refine ActiveSupport::TimeWithZone do
    def to_s(_format = :default)
      utc.iso8601(6)
    end
  end
end

class Export
  using ActiveSupportExtensions
  def export
    puts JSON.pretty_generate(User.last.as_json(only: [:created_at]))
  end
end

Export.new.export
# {
#   "created_at": "2022-04-05 14:36:07 -0700"
# }

While if I do a monkey patch, it does work

class ActiveSupport::TimeWithZone
  def to_s
    utc.iso8601(6)
  end
end

puts JSON.pretty_generate(User.last.as_json(only: [:created_at]))

# {
#   "created_at": "2022-04-05T21:36:07.878101Z"
# }

The only issue is that this overrides the entire applications TimeWithZone class, which is not something I want to do for obvious reasons.

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

1 participant