ActiveRecord::Errorsにあえて、削除やマージをつけてみる

<9/5 23:38 修正><10/15 23:36 修正2>

  • lib/extension.rb
module Extension  
  def included( recipient )
    recipient.extend self::ClassMethods
    _this_class = self
    recipient.class_eval { include _this_class::InstanceMethods }
  end
  alias_method :extended, :included
end
  • lib/errors_extension.rb
module ErrorsExtension
  extend Extension

  # クラスメソッド定義
  module ClassMethods
  end

  # インスタンスメソッド定義
  module InstanceMethods
    def +(other)
      self.instance_variable_get('@errors').merge other.instance_variable_get('@errors')
    end
    alias_method(:merge, :'+')

    def delete(key)
      self.instance_variable_get('@errors').delete(key)
    end
    
    def merge!(other)
      self.instance_variable_get('@errors').merge!(other.instance_variable_get('@errors'))
    end
  end
end

ActiveRecord::Errors.extend ErrorsExtension
  • config/initializers/errors_extension.rb
require 'errors_extension'