LoginSignup
0
1

More than 5 years have passed since last update.

オープンクラスでメソッドチェインできるrubyプログラムの書き方

Last updated at Posted at 2017-09-27

メソッドチェイン愛好会会員です

元の記事
全部のファイルを結合するrubyプログラム
メソッドチェインできるrubyプログラムの書き方

組み込みクラスにメソッドを追加して、メソッドチェインできるようにしました。
レシーバを意識してメソッドを追加すればいいということが分かります。
delete_myselfメソッドもprivateかmoduleに隠蔽したくて調べたがよく分からず、とりあえずArrayクラスに追加。

前回の記事から、文字数カウント、行数カウント、ファイル名を文中に追記する機能を追加しました。
少しだけ全体をリファクタリング済み。

設計とリファクタリングの本を熟読したら、もう少し綺麗に書けそう。
もっと良い設計を知りたい。

method_chain_by_open_class.rb
# coding: utf-8
# about open class http://www.ruby.or.jp/ja/tech/development/ruby/tutorial/090_class_extension.html


class String
    def glob_by_extension
        all_files = Dir.glob("**/*."+self)
        all_files = all_files.delete_myself
        return all_files
    end

    def count_lines
        return self.count("\n")
    end

    def file_write(name)
        File.write name, self
    end

    def file_write_ruby_ver_1_8(name)
    File.open(name,"w:EUC-JP:UTF-8") {|file| file << self }
    end
end


class Array
    def delete_myself
        self.delete(__FILE__) if self.include?(__FILE__)
        return self
    end

    def all_ary_to_str
        @str = ""
        self.each {|file| @str << txt_add(file) }
        return @str
    end

    def all_ary_with_name_to_str
        @str = ""
        self.each {|file| @str << txt_add_with_name(file) + txt_add(file) }
        return @str
    end

    private

    def txt_add(file)
        return File.read(file)
    end

    def txt_add_with_name(file)
        file_name_str = "-------------------------------------------------------"
        file_name_str += "\n" + file + "\n"
        file_name_str += "-------------------------------------------------------" + "\n"
        return file_name_str
    end
end

puts "rb".glob_by_extension.all_ary_to_str.length
#puts "rb".glob_by_extension.all_ary_to_str.count("\n")
puts "rb".glob_by_extension.all_ary_to_str.count_lines

#"rb".glob_by_extension.all_ary_to_str.file_write_ruby_ver_1_8("combining.rb")
"rb".glob_by_extension.all_ary_with_name_to_str.file_write_ruby_ver_1_8("combining.rb")

参考
定義済みクラスの拡張(オープンクラス)

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1