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



20
21
22
# File 'lib/sequent/core/helpers/param_support.rb', line 20

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

Instance Method Details

#as_paramsObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sequent/core/helpers/param_support.rb', line 49

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) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sequent/core/helpers/param_support.rb', line 24

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

    next if value.blank?
    if type.respond_to? :from_params
      value = type.from_params(value)
    elsif type.is_a? Sequent::Core::Helpers::ArrayWithType
      value = value.map do |v|
        if type.item_type.respond_to?(:from_params)
          type.item_type.from_params(v)
        else
          v
        end
      end
    end
    instance_variable_set(:"@#{attribute}", value)
  end
end

#to_params(root) ⇒ Object



45
46
47
# File 'lib/sequent/core/helpers/param_support.rb', line 45

def to_params(root)
  make_params root, as_params
end