Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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