[ruby] make own DSL

原创文章,转载请注明来源并保留原文链接

Let’s take a look at below example:

class A

  def learn(&block)
    instance_eval(&block)
  end

  def a
    p 'aaaa'
  end

  def b
    p 'bbbb'
  end

  def c(str)
    p str * 2
  end

end

A.new.learn do
  a
  b
  c 'c'
end
# =>
# "aaaa"
# "bbbb"
# "cc"

We can make this form string:

class A
 
  def load(recipe)
    instance_eval(recipe)
  end

end

recipe = <<-RECIPE

a
b
c 'c'

RECIPE

A.new.load(recipe)
# =>
# "aaaa"
# "bbbb"
# "cc"

Leave a Reply

Your email address will not be published. Required fields are marked *