RubyでDSL作ってみる

肝となる処理

instance_eval が便利。

ブロック渡し以外にも、文字列を渡してインスタンス内のコンテキストで実行可能。

てことで

  1. DSL用のメソッドAを用意
  2. DSLで書かれたファイルを読み込む
  3. メソッドAと同じインスタンスで、ファイルの内容をinstance_eval
  4. -_-b

Example

DSL用のメソッドを持ったクラス

class DSL
  attr_reader :names

  def self.execute
    contents = File.open('DSLFile', 'rb'){ |f| f.read }
    dsl = new
    dsl.instance_eval(contents)

    p dsl.names
  end

  def initialize
    @names = []
  end

  def hello(name)
    @names << name
  end
end

DSLファイル

hello 'world'
hello 'again'
hello 'kitty'

実行してみる

DSL.execute

["world", "again", "kitty"]