Created
February 21, 2015 02:18
-
-
Save masterkain/a192c5982f5c46f80ebd to your computer and use it in GitHub Desktop.
custom rails json dump load class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'oj' | |
# Macro in model: | |
# serialize :payload, ActiveSupport::OJSON | |
# | |
# payload is a text data type in postgres | |
# | |
module ActiveSupport | |
module OJSON | |
class << self | |
PARSE_ERROR_CLASS = defined?(::Oj::ParseError) ? ::Oj::ParseError : SyntaxError | |
# Parses a JSON string (JavaScript Object Notation) into a hash. | |
# See www.json.org for more info. | |
# | |
# ActiveSupport::OJSON.decode("{\"team\":\"rails\",\"players\":\"36\"}") | |
# => {"team" => "rails", "players" => "36"} | |
def decode(string, options = {}) | |
options.reverse_merge!(mode: :strict, symbolize_keys: false) | |
options[:symbol_keys] = options.delete(:symbolize_keys) | |
::Oj.load(string, options) | |
end | |
alias_method :load, :decode | |
# Encode an object. | |
# ActiveSupport::OJSON.encode(test: 'value') | |
def encode(object, options = {}) | |
options.reverse_merge!(mode: :compat, time_format: :ruby) | |
options.merge!(indent: 2) if options[:pretty] | |
::Oj.dump(object, options) | |
end | |
alias_method :dump, :encode | |
# Returns the class of the error that will be raised when there is an | |
# error in decoding JSON. Using this method means you won't directly | |
# depend on the ActiveSupport's JSON implementation, in case it changes | |
# in the future. | |
# | |
# begin | |
# obj = ActiveSupport::OJSON.decode(some_string) | |
# rescue ActiveSupport::JSON.parse_error | |
# Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}") | |
# end | |
def parse_error | |
PARSE_ERROR_CLASS | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment