summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2015-04-08 13:31:28 -0600
committermo khan <mo@mokhan.ca>2015-04-08 13:31:28 -0600
commit94c3bce39bb454dbb557dd3730ac56457540130e (patch)
tree68e1a34f126d91fffdecf442f2d88c4963f958e9
parent81f1e9d793c896953f645e46331854e4c7127ea0 (diff)
build hacky dsl engine.
-rw-r--r--lib/scale.rb1
-rw-r--r--lib/scale/dsl.rb40
-rw-r--r--spec/dsl_spec.rb22
3 files changed, 63 insertions, 0 deletions
diff --git a/lib/scale.rb b/lib/scale.rb
index 707d49f..dd41d40 100644
--- a/lib/scale.rb
+++ b/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!
diff --git a/lib/scale/dsl.rb b/lib/scale/dsl.rb
new file mode 100644
index 0000000..99fefb4
--- /dev/null
+++ b/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
diff --git a/spec/dsl_spec.rb b/spec/dsl_spec.rb
new file mode 100644
index 0000000..55d9f78
--- /dev/null
+++ b/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