Module: Sequent::Core::Helpers::ParamSupport

Included in:
BaseCommand, ValueObject
Defined in:
lib/sequent/core/helpers/param_support.rb

Overview

Class to support binding from a params hash like the one from Sinatra

You typically do not need to include this module in your classes. If you extend from Sequent::Core::ValueObject, Sequent::Core::Event or Sequent::Core::BaseCommand you will get this functionality for free.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(host_class) ⇒ Object

extend host class with class methods when we’re included



29
30
31
# File 'lib/sequent/core/helpers/param_support.rb', line 29

def self.included(host_class)
  host_class.extend(ClassMethods)
end

Instance Method Details

#as_paramsObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/sequent/core/helpers/param_support.rb', line 60

def as_params
  hash = HashWithIndifferentAccess.new
  self.class.types.each do |field|
    value = instance_variable_get("@#{field[0]}")
    next if field[0] == 'errors'

    hash[field[0]] = if value.is_a?(Array)
                       next if value.blank?

                       value.map { |v| value_to_string(v) }
                     else
                       value_to_string(value)
                     end
  end
  hash
end

#from_params(params, strict_nil_check = true) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sequent/core/helpers/param_support.rb', line 33

def from_params(params, strict_nil_check = true)
  params = HashWithIndifferentAccess.new(params)
  self.class.types.each do |attribute, type|
    value = params[attribute]

    next if strict_nil_check && value.nil?
    next if !strict_nil_check && value.blank?

    if type.respond_to? :from_params
      value = type.from_params(value)
    elsif value.is_a?(Array)
      value = value.map do |v|
        if type.item_type.respond_to?(:from_params)
          type.item_type.from_params(v, strict_nil_check)
        else
          v
        end
      end
    end
    instance_variable_set(:"@#{attribute}", value)
  end
end

#to_params(root) ⇒ Object



56
57
58
# File 'lib/sequent/core/helpers/param_support.rb', line 56

def to_params(root)
  make_params root, as_params
end