Last active
October 6, 2015 19:44
-
-
Save tarot/01789a80de9cfaa117f2 to your computer and use it in GitHub Desktop.
空配列と空ハッシュで改行しないJSON.pretty_generate 先にjson/extがロードされてても大丈夫版
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 'json' | |
require 'json/pure/generator' | |
module Generator | |
module GeneratorMethods | |
(JSON::Pure::Generator::GeneratorMethods.constants - %i(Array Hash Integer)).each do |constant| | |
const_set constant, JSON::Pure::Generator::GeneratorMethods.const_get(constant) | |
end | |
%i(Fixnum Bignum).each do |constant| | |
const_set constant, JSON::Pure::Generator::GeneratorMethods::Integer | |
end | |
module Array | |
include JSON::Pure::Generator::GeneratorMethods::Array | |
def to_json(*) | |
empty? ? '[]' : super | |
end | |
end | |
module Hash | |
include JSON::Pure::Generator::GeneratorMethods::Hash | |
alias_method :pure_to_json, :to_json | |
def to_json(state = nil, *) | |
empty? ? '{}' : sort.to_h.pure_to_json(state) | |
end | |
end | |
end | |
class State < JSON::Pure::Generator::State; end | |
end | |
desc 'normalize a.json' | |
task :normalize do | |
filename = 'a.json' | |
JSON.generator = Generator | |
src = File.open(filename) { |io| JSON.load(io) } | |
File.open(filename, 'w') { |io| io.write(JSON.pretty_generate(src)) } | |
end |
Author
tarot
commented
Oct 6, 2015
- railsのrakeタスクで使いたいので先にjson/extがロードされてても大丈夫なようにしたい
- json/extのGeneratorはFixnumとBignumのがあるけど、json/pureはIntegerにまとめられてる
- 先にjson/extがロードされてると、FixnumとBignumでエラーになる(pureのStateでextのGeneratorが呼ばれるから)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment