Extend model with context that contains validations

July 28, 2018

Imagine that you need conditional validation and you can't use ReForm or other form objects while extending third-party logic.
Then you can add custom context to model instance:

client = Client.find(id)
client.extend(Client::RegistrationContext)

module Client::RegistrationContext
  def self.extended(model)
    class << model
      validates :terms_of_service, acceptance: true
    end
  end

  attr_accessor :terms_of_service
end

Validates method is not available in the module context so we need to call it in the model context.

Extend model with context that contains validations - July 28, 2018 - {"name"=>"Stanislav Knyazev", "email"=>"extazystas@gmail.com"}