Hatena::ブログ(Diary)

わからん

2011.12.23

[] rak gem で使われていたコード生成テクニックの要点

rak gem を読んだときのメモです。

class Rak

  ...

  # this is tricky thing. Ignore the "code <<" to see the
  # logic. Because the options never change we conditionally compile
  # the match method based on them. This is gives a 2x speedup over
  # the alternative.
  def self.compile_match_file

    flag = '引数から取得した値'

    code = []
    code << %{def self.f       }
    code << %{  puts 1111      }
    code << %{  puts 2222      }
                if flag
    code << %{    puts 3333    }
                end
    code << %{end              }

    module_eval code.join("\n"), "#{__FILE__} (#{__LINE__})"

  end

  compile_match_file

  def self.run
    f
  end

end

Rak.run
# >> 1111
# >> 2222
# >> 3333
Google