views:

92

answers:

1

In Ruby on Rails, where does one put the code from this snippet in http://gist.github.com/376389? I want to extend ActiveRecord::Errors with the code that's available there so I can merge error messages.

Is this something for ApplicationController? or for lib?


Paste from github.com

# monkey patch gleaned from http://dev.rubyonrails.org/attachment/ticket/11394/merge_bang_errors.patch
module ActiveRecord
  class Errors

    def merge!(errors, options={})
      fields_to_merge = if only=options[:only]
        only
      elsif except=options[:except]
        except = [except] unless except.is_a?(Array)
        except.map!(&:to_sym)
        errors.entries.map(&:first).select do |field|
          !except.include?(field.to_sym)
        end
      else
        errors.entries.map(&:first)
      end
      fields_to_merge = [fields_to_merge] unless fields_to_merge.is_a?(Array)
      fields_to_merge.map!(&:to_sym)

      errors.entries.each do |field, msg|
        add field, msg if fields_to_merge.include?(field.to_sym)
      end
    end
  end
end
+3  A: 

You can just drop that into any ruby file in your initializers directory (create a new one, name it whatever you want). Rails runs all of the files in there every time it is booted, and will extend Errors at that time.

ryeguy