Module: IdEcuador::ModelAdditions
- Defined in:
- lib/id_ecuador/model_additions.rb
Overview
Módulo que agrega funcionalidad a los modelos de Rails Permite llamar a validates_id dentro de un modelo de Rails
Instance Method Summary collapse
Instance Method Details
#validates_id(attribute, options = {}) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/id_ecuador/model_additions.rb', line 13 def validates_id(attribute, ={}) # parse options: defaults = { allow_blank: true, message: nil, only: [] } # options for :only: [:cedula, :ruc, :sociedad_publica, :sociedad_privada] = defaults.merge # transform options[:only] to array if it's not: unless [:only].class == Array [:only] = [[:only]] end # poner métodos: # getter del atributo que siempre retorna una instancia de IdEcuador::Id y se encarga de hacer cache basado en el valor del atributo class_eval <<-EVAL def #{attribute}_id_validator if not @id_ecuador_validator or (send(:#{attribute}) != @id_ecuador_validator_last_id) @id_ecuador_validator = IdEcuador::Id.new(send(:#{attribute})) @id_ecuador_validator_last_id = send(:#{attribute}) end @id_ecuador_validator end EVAL # extensiones para #tipo_id, #tipo_id_sym y #codigo_provincia class_eval <<-EVAL def #{attribute}_tipo_id #{attribute}_id_validator.tipo_id end def #{attribute}_tipo_id_sym #{attribute}_id_validator.tipo_id_sym end def #{attribute}_codigo_provincia #{attribute}_id_validator.codigo_provincia end EVAL # método de validación validate do # Agregar error si <tt>allow_blank</tt> es <tt>false</tt> y <tt>attribute</tt> está en blanco if not [:allow_blank] and send(:"#{attribute}").blank? errors.add attribute.to_sym, ([:message] or "No puede quedar en blanco") else # normal validations: if not send(:"#{attribute}").blank? and not send(:"#{attribute}_id_validator").valid? if [:message] # poner <tt>options[:message]</tt> si algo está mal errors.add attribute.to_sym, [:message] else # poner los mensajes por defecto si no hay un <tt>options[:message]</tt> send(:"#{attribute}_id_validator").errors.each do |error| errors.add attribute.to_sym, error end end end # for options: if not [:only].empty? and not send(:"#{attribute}").blank? unless [:only].include?(send(:"#{attribute}_id_validator").tipo_id_sym) # si está especificado <tt>options[:only]</tt>, validar que el tipo de ID esté permitido errors.add attribute.to_sym, ([:message] or "Tipo de identificación no permitido") end end end end end |