Rails: how can I check this code that I entered in the lib / directory?

Having difficulty finding the correct mixing method in the code that I entered in the lib / directory for Rails 2.3.5.

I have several models that require a phone check. I had at least three models that used the same code, so I wanted to save DRY stuff and move them to the lib / directory. I used to have this code in each model:

validate :phone_is_valid

Then I would have a phone_is_valid method in the model:

protected
def phone_is_valid
  # process a bunch of logic
  errors.add_to_base("invalid phone") if validation failed
end 

I moved this code to lib / phones /, and in lib / phones I have lib / phones / phone_validation.rb, and there I copied the phone_is_valid method.

, ? validate: phone_is_valid ? , errors.add_to_base , , DRY. , :

validate :Phones::PhoneValidation::phone_is_valid(number)

lib/phones/called lib/phones/phone_normalize.rb. , , . (555) 222-1212 - 5552221212 - . :: Phone_Normalize:: normalize_method (number)?

, :

  • lib ,
  • lib ,
+3
2

?

module Phones

  def self.included(base)
    base.send :extend, ClassMethods
  end

  module ClassMethods
    def validate_phone(*attr_names)
      #setup the config array eg. configuration = atrr.extract_options!
      validates_each(attr_names, configuration) do |record, attr_name, value|
          record.errors.add(attr_name, configuration[:message]) unless #validation
       end
       #setup the phone normalization
       unless configuration[:normalize]
         before_save do
           # normalization code here
         end
       end
    end
  end
end

ActiveRecord::Base.send :include, Phones

:

validate_phone :main_phone, :cellphone, :message => "not a valid telephone number"
+1
class Profile < ActiveRecord::Base
  include Phones::PhoneValidation
  validate_phone_is_valid
end

, ActiveRecord:

module ActiveRecord
  module Validations
    module ClassMethods
      def validates_photo(*attr_names)
        # ....
      end
    end
  end
end
+2

Source: https://habr.com/ru/post/1744640/


All Articles