Programmatically copying ActiveModel validators from one model to another?

I’m writing a library that will require programmatically copying
validations from one model to another, but I’m stumped on how to pull

I have a model that is an ActiveModel::Model with some validation:

class User < ActiveRecord::Base
  validates :name, presence: true

And another model that I’d like to have the same validations:

class UserForm
  include ActiveModel::Model
  attr_accessor :name

Now I’d like to give UserForm the same validations as User, and
modifying User. Copying the validators over doesn’t work, because
ActiveModel::Validations hooks into callbacks during the validation

UserForm._validators = User._validators
# => true             # We wanted to see `false` here, but no

# are actually running because the :validate
# is empty.

Unfortunately, there doesn’t seem to be an easy way that I can see to
programmatically give one model another’s validation callbacks and still
have it work. I think my best bet is if I can ask Rails to regenerate
validation callbacks based on the validators that are present at a given
moment in time.

Is that possible? If not, is there a better way to do this?

Why don’t you try creating a concern and decorate the class with that
concern that contains the validations?

you can have a look here:

does this needs to be done in run time?

hope it helps.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs