概要
標準入出力処理時のValidationをクラスマクロで共通化
内容
標準入出力処理時のValidationをクラスマクロで共通化します。
仕様
・standard_ioモジュールをインポートすることで標準入力に対するValidationが利用可能になる
・[validate_args_counts n]で引数の数をチェック。nは任意の数値
・[validate_us_dollar index]でUSドルのチェック。indexはチェック対象の標準入力のindex。整数値で設定。
・[validate_file index]でUSドルのチェック。indexはチェック対象の標準入力のindex。整数値で設定。
・[validate]メソッドを実行すると、宣言した上記validationと自分で追加定義したValidationがすべて実行される。結果はture,false。
コマンドプロンプトでの利用前提のためエラー情報は一切なし
・Validation用のメソッド名は規約としてvalidate_xxxxとする
サンプルコード
共通モジュール:standard_io.rb
# encoding: utf-8 module StandardIo def self.included(klazz) klazz.extend(ClassMethods) end def validate self.methods.grep(/^validate_.*/).each do |m| return false unless method(m).call end true end def args_has_index?(index) $*.size > index end module ClassMethods def validate_args_counts(count) define_method "validate_args_counts" do $*.size == count end end def validate_us_dollar(index) define_method "validate_us_dollar_#{index}" do return false unless args_has_index?(index) if ($*[index] =~ /^[\d\.]+$/) return true end false end end def validate_file(index) define_method "validate_file_#{index}" do return false unless args_has_index?(index) FileTest.exist?($*[index]) end end end end
利用側モジュール:standard_io_user.rb
# encoding: utf-8 require_relative "standard_io" class Hoge include StandardIo validate_args_counts 4 validate_us_dollar 0 validate_us_dollar 1 validate_file 2 validate_file 3 def validate_range() _validate_range(0, (1..3)) end def _validate_range(index, range) range.include?($*[index].to_i) end end hoge = Hoge.new puts hoge.validate
出力
$ls standard_io.rb standard_io.yml standard_io_user.rb $ruby standard_io_user.rb 1 1 standard_io.rb standard_io.yml true $ruby standard_io_user.rb 0 1 standard_io.rb standard_io.yml false $ruby standard_io_user.rb 1 a standard_io.rb standard_io.yml false $ruby standard_io_user.rb 1 1 standard_io.rb standard_io.ymla false