Hi all
I’m just exploring a bit the source code of Rails, and I looked at the
methods
validates_exclusion_of
validates_inclusion_of
The source code of both them is up to 99% exactly the same:
# File vendor/rails/activerecord/lib/active_record/validations.rb,
line 602
602: def validates_exclusion_of(*attr_names)
603: configuration = { :message =>
ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
604: configuration.update(attr_names.pop) if
attr_names.last.is_a?(Hash)
605:
606: enum = configuration[:in] || configuration[:within]
607:
608: raise(ArgumentError, “An object with the method include? is
required must be supplied as the :in option of the configuration hash”)
unless enum.respond_to?(“include?”)
609:
610: validates_each(attr_names, configuration) do |record,
attr_name, value|
611: record.errors.add(attr_name, configuration[:message]) if
enum.include?(value)
612: end
613: end
# File vendor/rails/activerecord/lib/active_record/validations.rb,
line 575
575: def validates_inclusion_of(*attr_names)
576: configuration = { :message =>
ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
577: configuration.update(attr_names.pop) if
attr_names.last.is_a?(Hash)
578:
579: enum = configuration[:in] || configuration[:within]
580:
581: raise(ArgumentError, “An object with the method include? is
required must be supplied as the :in option of the configuration hash”)
unless enum.respond_to?(“include?”)
582:
583: validates_each(attr_names, configuration) do |record,
attr_name, value|
584: record.errors.add(attr_name, configuration[:message])
unless enum.include?(value)
585: end
586: end
The only difference is on line 584/611. One neeeds if and the other one
needs unless.
Isn’t this a massive injure of the DRY principle? Couldn’t this have
been coded much cleaner by using the same method for both and only
switch if to unless when using the one or the other validation?
Thanks for your opinions,
Joshua