Skip to content

Instantly share code, notes, and snippets.

@Plotist
Created May 18, 2021 20:54
Show Gist options
  • Save Plotist/bdf880c8c0ed6db609a84361d5a1a665 to your computer and use it in GitHub Desktop.
Save Plotist/bdf880c8c0ed6db609a84361d5a1a665 to your computer and use it in GitHub Desktop.
Forces automatic date parsing for JSON inside specific module (SomeapiService)
# lib/someapi_service/json.rb
module SomeapiService
class << ::ActiveSupport::JSON
# Exposes ActiveSupport::JSON decoding regardless of global ActiveSupport.parse_json_times.
# See https://api.rubyonrails.org/classes/ActiveSupport/JSON.html for more info.
#
# @note Only available in the context of SomeapiService module
def open_decode(json)
Time.use_zone('UTC') do
# User private function. Needs
convert_dates_from(::JSON.parse(json, quirks_mode: true))
end
end
end
module JSON
class << self
# Replaces standart JSON parsing with ActiveSupport::JSON
# @abstract
#
# @note Replacement applied only in the context of SomeapiService module
#
# @example within SomeapiService module
#
# module SomeapiService
# ...
#
# JSON.parse( "{\"dt_created\":\"2021-05-13 23:02:50\",\"dt_updated\":\"2021-05-13 23:02:50\"}")
#
# => {
# "dt_created" => Thu, 13 May 2021 23:02:50 UTC00:00,
# "dt_updated" => Thu, 13 May 2021 23:02:50 UTC00:00
# }
# @example outside SomeapiService module
#
# JSON.parse( "{\"dt_created\":\"2021-05-13 23:02:50\",\"dt_updated\":\"2021-05-13 23:02:50\"}")
#
# => {
# "dt_created" => "2021-05-13 23:02:50",
# "dt_updated" => "2021-05-13 23:02:50"
# }
def parse(json)
ActiveSupport::JSON.open_decode(json)
end
end
end
end
# lib/someapi_service.rb
#...
include SomeapiService::JSON
#...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment