ruby Stringにインデント用メソッドを追加
コード自動生成スクリプトを書いていてほしくなったので作成してみた。ただし文字列の追加にindentメソッドを利用する必要があるのでちょっと気持ち悪い(できれば<<とかで追加したい)。しかもこのメソッド、作成しただけでまだ未使用なので使い勝手も未知数。
使い方
require './Indent.rb' def foo src.indent "class X {" do |s| s.indent << STR void a(); void b(); STR s.indent "enum Y {" do |ss| ss.indent <<STR AAA, BBB, CCC STR ss.indent "};" end src.indent "};" end end # 出力結果 foo => class X { void a(); void b(); enum Y { AAA, BBB, CCC }; };
実装
Indent.rb
class String # インデントに使用する文字列 attr_accessor :indent_str def indent(text, &block) # ネストの深さ @depth = 0 unless @depth @indent_str = "\t" unless @indent_str real_indent_str = @depth * @indent_str self << text.gsub(/^/, "#{real_indent_str}") if block @depth += 1 block.call self @depth -= 1 end self end end