Class: StructuredParams::Params

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Attributes, ActiveModel::Model
Defined in:
lib/structured_params/params.rb

Overview

Parameter model that supports structured objects and arrays

Usage example:

class UserParameter < StructuredParams::Params
  attribute :name, :string
  attribute :address, :object, value_class: AddressParameter
  attribute :hobbies, :array, value_class: HobbyParameter
  attribute :tags, :array, value_type: :string
end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Params

: (Hash[untyped, untyped]|::ActionController::Parameters) -> void



65
66
67
68
# File 'lib/structured_params/params.rb', line 65

def initialize(params)
  processed_params = process_input_parameters(params)
  super(**processed_params)
end

Class Method Details

.permit_attribute_namesObject

Generate permitted parameter structure for Strong Parameters : () -> Array



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/structured_params/params.rb', line 25

def permit_attribute_names
  attribute_types.map do |name, type|
    name = name.to_sym

    if type.is_a?(Type::Object) || type.is_a?(Type::Array)
      { name => type.permit_attribute_names }
    else
      name
    end
  end
end

.structured_attributesObject

Get structured attributes and their classes : () -> Hash[Symbol, singleton(::StructuredParams::Params)]



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/structured_params/params.rb', line 39

def structured_attributes
  @structured_attributes ||= attribute_types.each_with_object({}) do |(name, type), hash|
    next unless structured_params_type?(type)

    hash[name] = if type.is_a?(Type::Array)
                   type.item_type.value_class
                 else
                   type.value_class
                 end
  end
end

Instance Method Details

#attributes(symbolize: false, compact_mode: :none) ⇒ Object

Convert structured objects to Hash and get attributes : (?symbolize: false, ?compact_mode: :none | :nil_only | :all_blank) -> Hash[String, untyped] : (?symbolize: true, ?compact_mode: :none | :nil_only | :all_blank) -> Hash[Symbol, untyped]



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/structured_params/params.rb', line 78

def attributes(symbolize: false, compact_mode: :none)
  attrs = super()

  self.class.structured_attributes.each_key do |name|
    value = attrs[name.to_s]
    attrs[name.to_s] = serialize_structured_value(value, compact_mode: compact_mode)
  end

  result = symbolize ? attrs.deep_symbolize_keys : attrs

  case compact_mode
  when :all_blank
    result.compact_blank
  when :nil_only
    result.compact
  else
    result
  end
end

#errorsObject

: () -> ::StructuredParams::Errors



71
72
73
# File 'lib/structured_params/params.rb', line 71

def errors
  @errors ||= Errors.new(self)
end