Gender validation in multi-rail models

Hello everyone - this question is about checking gender, but I’m interested to know how you dealt with similar situations with much larger collections (for example, choosing a country).

I am working on a system that allows athletes to register for various events, and I am currently working on a good test at the gender level. My question is: what is the best, most DRY way to do the same test on different models?

Let's say I want to check the gender Eventand property User. I can create a helper for validates_eachwhich checks the values ​​to be included in a very short array ["male", "female"] before updating the attribute gender. But what if I want to access the same gender array in a block form_for, say, as an input to collection_select?

I work for one model - I declare a constant GENDERSin Eventand have a short class method

def self.genders
    GENDERS
end

to access forms. But where should I store the array if multiple models need access?

EDIT: One idea is to use the class method in the application controller. Any thoughts on how suitable this approach will be are great.

+3
4

. . lib/actions_as_gendered:

module ActsAsGendered
  GENDERS = ['male', 'female']

  def self.included(base)
    base.extend(ActsAsGenderedMethods)
  end

  module ActsAsGenderedMethods
    def acts_as_gendered
      extend ClassMethods
      include InstanceMethods

      validates_inclusion_of :gender, :in => GENDERS
    end
  end

  module ClassMethods
    def is_gendered?
      true
    end
  end

  module InstanceMethods
    def is_male
      gender = 'male'
    end

    def is_female
      gender = 'female'
    end

    def is_male?
      gender == 'male'
    end

    def is_female?
      gender == 'female'
    end
  end
end

, , , - GENDERS, acts_as_gendered ActiveRecord, .

config/initializers/gender.rb:

require 'acts_as_gendered'
ActiveRecord::Base.send(:include, ActsAsGendered)

, , :

class User < ActiveRecord::Base
  acts_as_gendered
end

, , :)

:. , act_as_gendered, :

def acts_as_gendered options={}
  config = {:allow_nil => false}
  config.merge(options) if options.is_a?(Hash)

  extend ClassMethods
  include InstanceMethods

  if config[:allow_nil]
    validates_inclusion_of :gender, :in => (GENDERS + nil)
  else
    validates_inclusion_of :gender, :in => GENDERS
  end
end

:

class User < ActiveRecord::Base
  acts_as_gendered :allow_nil => true
end

, , . .

+9

, . , -, , - , . , lib , .

+2

, . , (1) , (2), , , . , .rb:

MALE    = 'male'
FEMALE  = 'female'
GENDERS = [MALE, FEMALE]

, :

def male?
  return gender == MALE
end
+1
source

I would write a special validation plugin (say validates_gender). Then you should call:

class Event < ActiveRecord::Base
   validates_gender :gender
end

Take a copy of my validates_as_email and use this, replacing it with value =~ EMAIL_ADDRESS_REyour own logic.

-1
source

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


All Articles