Class: EasyParams::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, Types::Struct, Validation
Defined in:
lib/easy_params/base.rb

Overview

Implements validations logic and nesting structures

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Types::Struct

#array?, #coerce

Constructor Details

#initialize(params = {}) ⇒ Base

Returns a new instance of Base.



10
11
12
13
14
# File 'lib/easy_params/base.rb', line 10

def initialize(params = {})
  self.class.schema.each do |attr, type|
    public_send("#{attr}=", type.coerce(params[attr])) if params
  end
end

Class Method Details

.array(param_name, of:, normalize: nil, **validations) ⇒ Object



45
46
47
48
49
50
# File 'lib/easy_params/base.rb', line 45

def array(param_name, of:, normalize: nil, **validations)
  validates param_name, **validations if validations.any?
  type = EasyParams::Types::Array.of(EasyParams::Types.const_get(of.to_s.camelcase))
  type = customize_type(type, nil, &normalize)
  public_send(:attribute, param_name, type)
end

.attribute(param_name, type) ⇒ Object



21
22
23
24
25
# File 'lib/easy_params/base.rb', line 21

def attribute(param_name, type)
  attr_accessor param_name

  schema[param_name] = type
end

.each(param_name, normalize: nil, **validations, &block) ⇒ Object



31
32
33
34
35
36
# File 'lib/easy_params/base.rb', line 31

def each(param_name, normalize: nil, **validations, &block)
  validates param_name, **validations if validations.any?
  type = EasyParams::Types::Each.with_type(&block)
  type = customize_type(type, nil, &normalize)
  public_send(:attribute, param_name, type)
end

.has(param_name, normalize: nil, **validations, &block) ⇒ Object



38
39
40
41
42
43
# File 'lib/easy_params/base.rb', line 38

def has(param_name, normalize: nil, **validations, &block)
  validates param_name, **validations if validations.any?
  type = Class.new(EasyParams::Types::Struct.class).tap { |c| c.class_eval(&block) }.new
  type = customize_type(type, nil, &normalize)
  public_send(:attribute, param_name, type)
end

.nameObject



17
18
19
# File 'lib/easy_params/base.rb', line 17

def name
  'EasyParams::Base'
end

.schemaObject



27
28
29
# File 'lib/easy_params/base.rb', line 27

def schema
  @schema ||= {}
end

Instance Method Details

#attributesObject



71
72
73
# File 'lib/easy_params/base.rb', line 71

def attributes
  self.class.schema.to_h { |k, type| [k, type.array? ? send(k).to_a : send(k)] }
end

#to_hObject



79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/easy_params/base.rb', line 79

def to_h
  attributes.each.with_object({}) do |(key, value), result|
    result[key] = case value
                  when EasyParams::Types::StructsCollection
                    value.map(&:to_h)
                  when EasyParams::Types::Struct.class
                    value.to_h
                  else
                    value
                  end
  end
end