Skip to content
Browse files

Pretty printer for records

Change-Id: Ie81b6f305a55804a7f752fa629c649aaaed23022
  • Loading branch information...
1 parent ccce19b commit 07e1e314547c230928504767580f7ef636f11cb5 mpage committed May 15, 2012
Showing with 66 additions and 0 deletions.
  1. +42 −0 lib/membrane/schema_parser.rb
  2. +24 −0 spec/schema_parser_spec.rb
View
42 lib/membrane/schema_parser.rb
@@ -4,6 +4,8 @@ module Membrane
end
class Membrane::SchemaParser
+ DEPARSE_INDENT = " ".freeze
+
class Dsl
OptionalKeyMarker = Struct.new(:key)
DictionaryMarker = Struct.new(:key_schema, :value_schema)
@@ -66,6 +68,8 @@ def deparse(schema)
"enum(%s)" % [schema.elem_schemas.map { |es| deparse(es) }.join(", ")]
when Membrane::Schema::List
"[%s]" % [deparse(schema.elem_schema)]
+ when Membrane::Schema::Record
+ deparse_record(schema)
else
schema.inspect
end
@@ -129,4 +133,42 @@ def parse_record(schema)
Membrane::Schema::Record.new(parsed, optional_keys)
end
+
+ def deparse_record(schema)
+ lines = ["{"]
+
+ schema.schemas.each do |key, val_schema|
+ dep_key = nil
+ if schema.optional_keys.include?(key)
+ dep_key = "optional(%s)" % [key.inspect]
+ else
+ dep_key = key.inspect
+ end
+
+ dep_val_schema_lines = deparse(val_schema).split("\n")
+
+ dep_val_schema_lines.each_with_index do |line, line_idx|
+ to_append = nil
+
+ if 0 == line_idx
+ to_append = "%s => %s" % [dep_key, line]
+ else
+ # Indent continuation lines
+ to_append = DEPARSE_INDENT + line
+ end
+
+ # This concludes the deparsed schema, append a comma in preparation
+ # for the next k-v pair.
+ if dep_val_schema_lines.size - 1 == line_idx
+ to_append += ","
+ end
+
+ lines << to_append
+ end
+ end
+
+ lines << "}"
+
+ lines.join("\n")
+ end
end
View
24 spec/schema_parser_spec.rb
@@ -59,6 +59,30 @@
parser.deparse(list_schema).should == "[dict(String, Integer)]"
end
+
+ it "should deparse elem schemas of a Membrane::Schema::Record schema" do
+ str_schema = Membrane::Schema::Class.new(String)
+ int_schema = Membrane::Schema::Class.new(Integer)
+ dict_schema = Membrane::Schema::Dictionary.new(str_schema, int_schema)
+
+ int_rec_schema = Membrane::Schema::Record.new({:str => str_schema,
+ :dict => dict_schema})
+
+ rec_schema = Membrane::Schema::Record.new({"str" => str_schema,
+ "rec" => int_rec_schema,
+ "int" => int_schema})
+ exp_deparse =<<EOT
+{
+"str" => String,
+"rec" => {
+ :str => String,
+ :dict => dict(String, Integer),
+ },
+"int" => Integer,
+}
+EOT
+ parser.deparse(rec_schema).should == exp_deparse.strip
+ end
end
describe "#parse" do

0 comments on commit 07e1e31

Please sign in to comment.
Something went wrong with that request. Please try again.