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



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

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

Instance Method Details

#as_paramsObject



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

def as_params
  hash = HashWithIndifferentAccess.new
  self.class.types.each do |field|
    value = self.instance_variable_get("@#{field[0]}")
    next if field[0] == "errors"
    hash[field[0]] = if value.kind_of?(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



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

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



54
55
56
# File 'lib/sequent/core/helpers/param_support.rb', line 54

def to_params(root)
  make_params root, as_params
end