メールを送る時のバリデーションをどうしようかと思ったんだけど、どうせだからActiveRecordのバリデーションが使えないかという話。
参考サイト
http://railsapi.masuidrive.jp/module/ActiveRecord%3A%3AValidations#const_VALIDATIONS
http://d.hatena.ne.jp/moro/20060419/1145461336
けど自分で実装した方が早いかもね・・・
というわけで、validateとvalid?だけ実装したオリジナルクラスです。
まぁとりあえずこれだけあれば十分でしょう。
追記:
というわけで実装。
これを継承すればOK。
validates~がないけど、個人的にあれはあんまり好きではないので、これでいいかと思います。
#バリデーションつきクラス
class ValidateClassdef initialize(attributes = nil)
self.attributes = attributes
enddef errors
@errors ||= ActiveRecord::Errors.new(self)
enddef attributes
@attributes
enddef attributes=(args)
return unless args.is_a?(Hash)
@attributes = argsargs.stringify_keys!
args.each do |key, value|
self.send(key.to_s + “=”, value) if self.respond_to?(key.to_s + “=”)end
enddef [](attr_name)
begin
return self.send(attr_name.to_s)
rescue NoMethodError
return nilend
end
#String.humanizeはrailsの拡張
def human_attribute_name(attr)
attr.humanize
enddef self.human_attribute_name(attr)
attr.humanize
enddef valid?
errors.clearvalidate
if errors.size > 0
return false
else
return true
end
enddef validate
endend