Reputation: 48450
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
Upvotes: 0
Views: 1200
Reputation: 55
This question is stale but if you want to do something similar in rails 3.x you can drop this in a file in your config/initializers/ directory:
# monkey patch gleaned from http://dev.rubyonrails.org/attachment/ticket/11394/merge_bang_errors.patch
module ActiveModel
class Errors
def merge!(errors, options={})
return if errors.blank? || errors.first.size < 2
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
Upvotes: 0
Reputation: 66851
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.
Upvotes: 4