Class: ExplicitParameters::Parameters

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations, Enumerable
Defined in:
lib/explicit_parameters/parameters.rb

Defined Under Namespace

Classes: CoercionValidator, RequiredValidator

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Parameters

Returns a new instance of Parameters.



58
59
60
61
# File 'lib/explicit_parameters/parameters.rb', line 58

def initialize(attributes = {})
  @original_attributes = attributes.stringify_keys
  super
end

Class Method Details

.accepts(name, type = nil, options = {}, &block) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/explicit_parameters/parameters.rb', line 35

def accepts(name, type = nil, options = {}, &block)
  type = define(name, &block) if block_given?
  attribute(name, type, options.slice(:default, :required))
  validations = options.except(:default)
  validations[:coercion] = true
  validates(name, validations)
end

.define(name = nil, &block) ⇒ Object



27
28
29
# File 'lib/explicit_parameters/parameters.rb', line 27

def define(name = nil, &block)
  name_class(Class.new(self, &block), name)
end

.optional_attributesObject



43
44
45
# File 'lib/explicit_parameters/parameters.rb', line 43

def optional_attributes
  @optional_attributes ||= []
end

.parse!(params) ⇒ Object



23
24
25
# File 'lib/explicit_parameters/parameters.rb', line 23

def parse!(params)
  new(params).validate!
end

.requires(name, type = nil, options = {}, &block) ⇒ Object



31
32
33
# File 'lib/explicit_parameters/parameters.rb', line 31

def requires(name, type = nil, options = {}, &block)
  accepts(name, type, options.merge(required: true), &block)
end

Instance Method Details

#to_hashObject



80
81
82
# File 'lib/explicit_parameters/parameters.rb', line 80

def to_hash
  super.except(*missing_attributes)
end

#validate!Object

Raises:



63
64
65
66
# File 'lib/explicit_parameters/parameters.rb', line 63

def validate!
  raise InvalidParameters.new({errors: errors}.to_json) unless valid?
  self
end

#validate_attribute_coercion!(attribute_name, value) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/explicit_parameters/parameters.rb', line 72

def validate_attribute_coercion!(attribute_name, value)
  return unless @original_attributes.key?(attribute_name.to_s)
  attribute = attribute_set[attribute_name]
  return if value.nil? && !attribute.required?
  return if attribute.value_coerced?(value)
  errors.add attribute_name, "#{@original_attributes[attribute_name].inspect} is not a valid #{attribute.type.name.demodulize}"
end

#validate_attribute_provided!(attribute_name, value) ⇒ Object



68
69
70
# File 'lib/explicit_parameters/parameters.rb', line 68

def validate_attribute_provided!(attribute_name, value)
  errors.add attribute_name, "is required" unless @original_attributes.key?(attribute_name.to_s)
end