2

I've defined a class which is getting fat because of many validations defined in it. So, I created a custom validator which includes all validations specific to a given context, and it's working fine.

But the issue is that, while validaing any attribute, the options which are passed while defining a validation aren't getting considered.

Consider this Post class,

class Post
  include Mongoid::Document

  field :state
  field :description

  validates_with PublishableValidator, on: :publish
end

Now, while publishing a post, its description is mandatory. So I am validating it with publish context.

@post.valid?(:publish)

Custom validator for all publishable validations is defined as,

class PublishableValidator < ActiveModel::Validator
  include ActiveModel::Validations

  validates :description, presence: true, unless: :admin?

  def validate(post)
    self.class.validators.each do |validator|
      validator.validate(post)
    end
  end
end

Now, there is constraint in description validation that, for admin, don't run this validation( not a good idea but admin can do whatever they want :] ).

But when I validate it with blank description and admin privilege, it still gives error, without considering provided constraint.

Suggestions ??

Yogesh Khater
  • 1,690
  • 1
  • 15
  • 20

1 Answers1

2

I managed to solve it by using SimpleDelegator class.

  • First, I inherited PublishableValidator from SimpleDelegator.
  • Delegated PublishableValidator object to @post.
  • Ran validations on publishable object.
  • And last, merged publishable errors to post object.

Updated PublishableValidator

class PublishableValidator < SimpleDelegator
  include ActiveModel::Validations

  validates :description, presence: true, unless: :admin?

  def validate(post)
    self.__setobj__(post)
    super

    post.errors.messages.merge!(self.errors.messages)
  end
end

Thanks to this blog

Yogesh Khater
  • 1,690
  • 1
  • 15
  • 20