Last active
January 28, 2019 11:42
-
-
Save rwz/14c0d8a5187b69922bb4 to your computer and use it in GitHub Desktop.
Custom JSON types in AS 4.1+
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
# 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