From 49488e3757fb0c75736e97bacfa6631a95cbccef Mon Sep 17 00:00:00 2001 From: Justin Li Date: Wed, 21 Aug 2019 13:24:21 -0400 Subject: [PATCH] Add rake dump_portable_ast --- Rakefile | 6 ++++++ lib/liquid/ast_to_portable_json.rb | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 lib/liquid/ast_to_portable_json.rb diff --git a/Rakefile b/Rakefile index 9650abb..521e4f0 100755 --- a/Rakefile +++ b/Rakefile @@ -100,3 +100,9 @@ end task :console do exec 'irb -I lib -r liquid' end + +task :dump_portable_ast, [:filename] do |_task, args| + require 'liquid/ast_to_portable_json' + ast = Liquid::Template.parse(File.read(args[:filename])) + puts(Liquid::ASTToPortableJSON.dump(ast)) +end diff --git a/lib/liquid/ast_to_portable_json.rb b/lib/liquid/ast_to_portable_json.rb new file mode 100644 index 0000000..cb0dcdc --- /dev/null +++ b/lib/liquid/ast_to_portable_json.rb @@ -0,0 +1,27 @@ +require 'yaml' +require 'json' +require 'liquid' + +module Liquid + class ASTToPortableJSON + def self.dump(ast) + yaml = YAML.dump(ast) + yaml.gsub!(/---.*/, '') + yaml.gsub!(/!ruby\/object:(.+)\n(\s+)/, "\n\\2class_name: \\1\n\\2") + + bare_hash_ast = YAML.load(yaml) + delete_parse_context(bare_hash_ast) + JSON.pretty_generate(bare_hash_ast) + end + + def self.delete_parse_context(bare_hash_ast) + if bare_hash_ast.is_a?(Array) + bare_hash_ast.each { |v| delete_parse_context(v) } + elsif bare_hash_ast.is_a?(Hash) + bare_hash_ast.delete('parse_context') + bare_hash_ast.each { |k, v| delete_parse_context(v) } + end + end + end +end +