Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | メタなコードを書く際に完成予想図をコメントに書く

概要

メタなコードを書く際に完成予想図をコメントに書く

詳細

メタなコードを書く際に完成予想図をコメントに書く手法について。
今日コードリーディングでActiveSupportの SafeBufferクラスのコードを見ていた際にあった手法。

メタなコードはどうしてもコードをじっくり読まないと理解しにくい。
しかも単独でコードを読むだけではなくテストコードや利用コードを含めてどのように動作するか
理解する必要がある。
ActiveSupportではメタなロジックの後ろに、動的に生成されるメソッドがコメントされていた。

実物はこちら。
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/output_safety.rb

以下は、ActiveSupportの手法を参考にして作ったサンプルです。

サンプル

# encoding: utf-8
require 'tbpgr_utils'

class Hoge
  [:hoge, :hige].each do |method_name|
    define_method :"#{method_name}_method" do |*args|   # def hoge_method(*args)
      "hello #{method_name}"                            #   "hello hoge"
    end                                                 # end
  end
end

bulk_puts_eval binding, <<-EOS
Hoge.new.hoge_method
Hoge.new.hige_method
EOS

__END__
下記はTbpgrUtils gemの機能

bulk_puts_eval

詳しくは下記参照
https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

Hoge.new.hoge_method # => "hello hoge"
Hoge.new.hige_method # => "hello hige"