ExcelFileParser def initialize(filepath) @filename = filepath end def to_attributes base = File.basename(@filename, ”.xlsx”) if /\A◯◯株式会社様_\d{4}年\d{2}月\z/ =~ base to_attributes_a elsif /\A\d{6}_sales_statement\z/ =~ base to_attributes_c else raise "Unsupported file format." end end def to_attributes_a # ここはA社売上明細のパース処理 end def to_attributes_c # ここはC社売上明細のパース処理 end end end excel_file_parser.rb 同じファイル形式でも データフォーマットは異なるため、 ファイル名で判別して それぞれのフォーマットに合ったパース処理を 実装していた。
to_attributes base = File.basename(@filename, ”.xlsx”) if /\A◯◯株式会社様_\d{4}年\d{2}月\z/ =~ base || /\A\d{8}_Service_E_MEISAI\z/ =~ base to_attributes_a elsif /\A\d{6}_sales_statement\z/ =~ base to_attributes_c elsif /\A◯◯株式会社_販売レポート\z/ =~ base to_attributes_d elsif /\ASalesSiteF-ご利用明細\z/ =~ base to_attributes_f else raise "Unsupported file format." end end def to_attributes base = File.basename(@filename, ”.tsv”) if /\A\d{6}-sales-report\z/ =~ base to_attributes_b elsif /\A◯◯株式会社様御中_売上報告\z/ =~ base to_attributes_g else raise "Unsupported file format." end end excel_file_parser.rb tsv_file_parser.rb
基底クラスの抽象メソッド化したい メソッドに、Error(※)を仕込む。 module Reader class Base def initialize(filepath) @filepath = filepath end def parse_to_attributes raise NotImplementedError end end end base.rb これにより、オーバーライドされず にメソッドが呼び出されるとエラー が発生するようになる。 ※サンプルコードではNotImplementedErrorを使用していますが、Rubyにおいては本来抽象メソッドが実装されていない ことを示す用途として使うものではないようです。StandardErrorを継承していないという点も注意が必要です。