Module: ROM::Model::Validator::ClassMethods

Defined in:
lib/rom/model/validator.rb

Instance Method Summary collapse

Instance Method Details

#call(attributes) ⇒ Model::Attributes

Trigger validation for specific attributes

Parameters:

Returns:



155
156
157
158
# File 'lib/rom/model/validator.rb', line 155

def call(attributes)
  validator = new(attributes)
  validator.call
end

#embedded(name, options = {}, &block) ⇒ Object

Specify an embedded validator for nested structures

Examples:

class UserValidator
  include ROM::Model::Validator

  set_model_name 'User'

  embedded :address do
    validates :city, :street, :zipcode, presence: true
  end

  emebdded :tasks do
    validates :title, presence: true
  end
end

validator = UserAttributes.new(address: {}, tasks: {})

validator.valid? # false
validator.errors[:address].first # errors for address
validator.errors[:tasks] # errors for tasks


184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/rom/model/validator.rb', line 184

def embedded(name, options = {}, &block)
  presence = options.fetch(:presence, true)

  validator_class = Class.new {
    include ROM::Model::Validator
  }

  validator_class.set_model_name(name.to_s.classify)
  validator_class.class_eval(&block)

  embedded_validators[name] = validator_class

  validates name, presence: true if presence

  validate do
    value = attributes[name]

    if value.present?
      Array([value]).flatten.each do |object|
        validator = validator_class.new(object, root, attributes)
        validator.validate

        if validator.errors.any?
          errors.add(name, validator.errors)
        else
          errors.add(name, [])
        end
      end
    end
  end
end

#relation(name = nil) ⇒ Symbol

Set relation name for a validator

This is needed for validators that require database access

Examples:


class UserValidator
  include ROM::Model::Validator

  relation :users

  validates :name, uniqueness: true
end

Returns:

  • (Symbol)


134
135
136
137
# File 'lib/rom/model/validator.rb', line 134

def relation(name = nil)
  @relation = name if name
  @relation
end

#set_model_name(name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



140
141
142
143
144
145
146
# File 'lib/rom/model/validator.rb', line 140

def set_model_name(name)
  class_eval "    def self.model_name\n      @model_name ||= ActiveModel::Name.new(self, nil, \#{name.inspect})\n    end\n  RUBY\nend\n"