Commit 94c3bce

mo khan <mo@mokhan.ca>
2015-04-08 19:31:28
build hacky dsl engine.
1 parent 81f1e9d
Changed files (3)
lib/scale/dsl.rb
@@ -0,0 +1,40 @@
+module Scale
+  class DSL
+    def run
+      DSLBuilder.new.tap do |builder|
+        yield builder
+      end.to_xml
+    end
+  end
+
+  class DSLCommand
+    def initialize(name, args, block)
+      @name = name
+      @args = args
+      @block = block
+    end
+
+    def run(svg)
+      type = Kernel.const_get("Scale::#{@name.to_s.capitalize}")
+      svg.add(type.new(*@args))
+    end
+  end
+
+  class DSLBuilder
+    def initialize(commands = [])
+      @commands = commands
+    end
+
+    def method_missing(name, *args, &block)
+      @commands.push(DSLCommand.new(name, args, block))
+    end
+
+    def to_xml
+      svg = SVG.new
+      @commands.each do |command|
+        command.run(svg)
+      end
+      svg.to_xml
+    end
+  end
+end
lib/scale.rb
@@ -5,6 +5,7 @@ require "scale/shapes/rectangle"
 require "scale/shapes/circle"
 require "scale/shapes/ellipse"
 require "scale/text"
+require "scale/dsl"
 
 module Scale
   # Your code goes here... NOT!
spec/dsl_spec.rb
@@ -0,0 +1,22 @@
+describe Scale::DSL do
+  subject { Scale::DSL.new }
+
+  it 'produce the proper svg via the DSL' do
+    result = subject.run do |x|
+      x.rectangle(width: "100%", height: "100%", fill: "red")
+      x.circle(cx: 150, cy: 100, r: 80, fill: "green")
+      x.text("SVG", x: 150, y: 125, font_size: 60, text_anchor: 'middle', fill: "white")
+    end
+
+    expected = <<-XML
+<?xml version=\"1.0\"?>
+<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" baseProfile=\"full\">
+  <rect width=\"100%\" height=\"100%\" fill=\"red\"/>
+  <circle cx=\"150\" cy=\"100\" r=\"80\"/>
+  <text x=\"150\" y=\"125\">SVG</text>
+</svg>
+    XML
+
+    expect(result).to eql(expected)
+  end
+end