如何在Ruby中创建自定义DSL,如YAML,Cucumber,Markdown等?

时间:2013-08-19 21:27:05

标签: ruby dsl

我目前有一个基于Ruby的DSL,用于创建使用实例eval的幻灯片:

# slides.rb
slide {
  title 'Ruby Programming'
  subtitle 'A simple introduction'
  bullet 'First bullet'
  bullet 'Second bullet'
}

# implementation:
class DSL
  class Slide
    def title(title)
      @title = title
    end
    # ...etc...
  end

  def slide(&block)
    @slides << Slide.new.instance_eval(&block)
  end
end

dsl = DSL.new
dsl.instance_eval(File.read('slides.rb'))

结果是这样的:


Ruby Programming

简单介绍

  • 第一颗子弹
  • 第二个子弹

我想通过创建一个不使用Ruby语法的DSL来将其提升到新的水平。也许更像是YAML或Markdown:

title: Ruby Programming
subtitle: A simple introduction
* First bullet
* Second bullet

如何为这种语法创建DSL /解析器?

4 个答案:

答案 0 :(得分:2)

有人已经提到了Parslet,但我想我会演示它有多容易。

require 'parslet' 
require 'pp'

slides = <<EOS
  title: Ruby Programming
  subtitle: A simple introduction
  * First bullet
  * Second bullet
EOS

#Best to read the parser from the bottom up.

class SlidesParser < Parslet::Parser
    rule(:eol)          { str("\n") | any.absent? }
    rule(:ws?)          { match('[\s\t]').repeat(0) }
    rule(:rest_of_line) { ws? >> (str("\n").absent? >> any).repeat(1).as(:text) } 
    rule(:title)        { ws? >> str("title:")>> rest_of_line.as(:title) >> eol }
    rule(:subtitle)     { ws? >> str("subtitle:")>> rest_of_line.as(:subtitle) >> eol }
    rule(:bullet)       { ws? >> str("*") >> rest_of_line >> eol }
    rule(:bullet_list)  { bullet.repeat(1).as(:bullets) }
    rule(:slide)        { (title >> subtitle >> bullet_list).as(:slide) }
    root(:slide)
end

# Note: parts can be made optional by adding a ".maybe"  eg. => subtitle.maybe

result = SlidesParser.new.parse(slides)  
pp result
#{:slide=>
#  {:title=>{:text=>"Ruby Programming"@9},
#   :subtitle=>{:text=>"A simple introduction"@38},
#   :bullets=>[{:text=>"First bullet"@64}, {:text=>"Second bullet"@81}]}}

在Parslet中,解析器只是工作的一部分,因为它们只是将文本转换为红宝石结构。

然后使用转换来匹配/替换树节点以生成所需的结构。

# You can do lots of things here.. I am just replacing the 'text' element with their value
# You can use transforms to build your custom AST from the raw ruby tree 
class SlidesTransform < Parslet::Transform
  rule(:text => simple(:str))        { str }
  # rule(
  #    :title => simple(:title), 
  #    :subtitle => simple(:subtitle), 
  #    :bullets => sequence(:bullets)) { Slide.new(title, subtitle, bullets) }
end

pp SlidesTransform.new.apply(result)
#{:slide=>
#  {:title=>"Ruby Programming"@9,
#   :subtitle=>"A simple introduction"@38,
#   :bullets=>["First bullet"@64, "Second bullet"@81]}}

答案 1 :(得分:1)

也许值得一看当前的一些开源实现。

但我不得不问 - 你为什么要自己做?为什么不使用已有的? TOML很棒。

Ruby解析器实现:https://github.com/jm/toml

答案 2 :(得分:1)

我相信Cucumber uses Ragel用于解析器,这里是使用Ruby的decent looking intro to it ...

Treetop也很常见,还有Parslet

ANTLR,Rex和Racc ...各种处理外部DSL的方法。

Eloquent Ruby有一章关于外部DSL的创建,从基本的字符串解析和正则表达到使用Treetop ......

答案 3 :(得分:1)

您可以使用regexp进行基本解析。像这样:

slides = <<EOS
  title: Ruby Programming
  subtitle: A simple introduction
  * First bullet
  * Second bullet
EOS

regexp = %r{
  (title:\s+)(?<title>[^\n]*)|
  (subtitle:\s+)(?<subtitle>[^\n]*)|
  (\*\s+)(?<bullet>[^\n]*)
}x

tags = {
  'title' => 'h1',
  'subtitle' => 'h2',
  'bullet' => 'li'
}

fUL = false
slides.lines.each {|line|
  md = line.match(regexp)
  md.names.select{|k| md[k]}.each {|k|
    puts '<ul>' or fUL = true if k == 'bullet' && !fUL
    puts '</ul>' or fUL = false if k != 'bullet' && fUL
    puts "<#{tags[k]}>#{md[k]}</#{tags[k]}>"
  }
}
puts '</ul>' if fUL