Module: ContextValidations::Controller

Defined in:
lib/context_validations/controller.rb

Instance Method Summary collapse

Instance Method Details

#validates(*attributes) ⇒ Object

Instance level implementation of ‘ActiveModel::Validations.validates` Will accept all of the same options as the class-level model versions of the method



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/context_validations/controller.rb', line 46

def validates(*attributes)
  defaults = attributes.extract_options!
  validations = defaults.slice!(*_validates_default_keys)

  attributes.inject(@validations) do |validators, attribute|
    defaults[:attributes] = [attribute]
    validations.each do |key, options|
      key = "#{key.to_s.camelize}Validator"
      klass = key.include?('::') ? key.constantize : "ActiveModel::Validations::#{key}".constantize
      validator = klass.new(defaults.merge(_parse_validates_options(options)))
      validators << validator
    end
    validators
  end.flatten.uniq
end

#validations(context = nil) ⇒ Object

Will build the validations used to assign to a model instance

Passing a context will call the ‘#context_validations` method if available `#base_validations` will always be called prior to `#context_validations`

If you are using Ruby 2.0+ not passing a context will force an implicit context call based upon the calling method name.

examples:

# Implicit method call will call `#base_validations` then `#create_validations`
def create
  @user.validations = validations
end

# Will call `#base_validations` then `#create_validations`
def other_create
  @user.validations = validations(:create)
end

# Will onliy call `#base_validations` because `#update_validations` does not exist
def update
  @user.validations = validations
end

def create_validations
  ...
end

Parameters:

  • (String, Symbol)


31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/context_validations/controller.rb', line 31

def validations(context = nil)
  if RUBY_VERSION > '2'
    context ||= caller_locations(1, 1).first.label
  end
  @validations = []
  base_validations
  if respond_to?("#{context}_validations") || private_methods.include?("#{context}_validations".to_sym) ||
    protected_methods.include?("#{context}_validations".to_sym)
    send("#{context}_validations")
  end
  @validations
end