Skip to content

Instantly share code, notes, and snippets.

@rwz
Last active January 28, 2019 11:42
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwz/14c0d8a5187b69922bb4 to your computer and use it in GitHub Desktop.
Save rwz/14c0d8a5187b69922bb4 to your computer and use it in GitHub Desktop.
Custom JSON types in AS 4.1+
# config/initializers/lol_json.rb
module ActiveSupport
module JSON
module Encoding
class JSONGemEncoder
BYPASS_JSONIFY = Set.new
alias_method :original_jsonify, :jsonify
def jsonify(value)
BYPASS_JSONIFY.include?(value.class) ? value : original_jsonify(value)
end
end
end
end
end
# lib/compiled_json.rb
class CompiledJson
def initialize(s); @s = s; end
def to_json(*); @s; end
def as_json(*); self; end
end
ActiveSupport::JSON::Encoding::JSONGemEncoder::BYPASS_JSONIFY << CompiledJson
# seems to be working
bar = CompiledJson.new("bar")
MultiJson.dump(foo: bar) # => { "foo": bar }
{ foo: bar }.to_json # => { "foo": bar }
Jbuilder.encode{ |json| json.foo bar } # => { "foo": bar }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment