Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created February 5, 2013 13:27
Show Gist options
  • Save chikoski/4714449 to your computer and use it in GitHub Desktop.
Save chikoski/4714449 to your computer and use it in GitHub Desktop.

instance_eval を使った DSL作成の練習 main.rb を実行すると、次のように出力される。

hoge -> B -> E
B -> D
hoge -> C
n = Node.new("A") do
name "hoge"
b = Node.new("B") do
add Node.new("E")
add Node.new("D")
end
add b
add Node.new("C")
end
puts n.to_s
require 'digest/md5'
class Node
attr_accessor :label
attr_reader :neighbors
def initialize(label=Digest::MD5.hexdigest(rand.to_s), &block)
@neighbors = []
@label = label
instance_eval(&block) if block_given?
end
def to_s
if neighbors.length > 0
ret = ""
neighbors.each do |n|
ret += "#{label} -> #{n.to_s}\n"
end
return ret.gsub(/\n+/, "\n")
else
return label
end
end
def add(node)
@neighbors << node
end
def name(l)
@label = l
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment