Class: Zoom::Params

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/zoom/params.rb

Constant Summary collapse

EMPTY_ARRAY =
[].freeze
EMPTY_HASH =
{}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(parameters = {}) ⇒ Params

delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?,

:include?, :as_json, :to_s, :each_key, to: :@parameters


8
9
10
11
# File 'lib/zoom/params.rb', line 8

def initialize(parameters = {})
  @parameters = parameters
  super
end

Instance Method Details

#except(*keys) ⇒ Object



33
34
35
# File 'lib/zoom/params.rb', line 33

def except(*keys)
  dup.except!(keys.flatten)
end

#except!(keys) ⇒ Object



37
38
39
40
# File 'lib/zoom/params.rb', line 37

def except!(keys)
  keys.each { |key| delete(key) }
  self
end

#find_missing_keys(keys) ⇒ Object



58
59
60
61
62
# File 'lib/zoom/params.rb', line 58

def find_missing_keys(keys)
  keys.each_with_object([]) do |k, array|
    array << k if self[k].nil?
  end
end

#hash_filter(filter) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/zoom/params.rb', line 45

def hash_filter(filter)
  # Slicing filters out non-declared keys.
  slice(*filter.keys).each do |key, value|
    next unless value
    next unless key? key
    next if filter[key] == EMPTY_ARRAY
    next if filter[key] == EMPTY_HASH
    # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
    self.class.new(value).permit(filter[key])
  end
  filter.keys
end

#permit(*filters) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/zoom/params.rb', line 20

def permit(*filters)
  permitted_keys = filters.flatten.each_with_object([]) do |filter, array|
                     case filter
                     when Symbol, String
                       array << filter
                     when Hash
                       array << hash_filter(filter)
                     end
                   end
  non_permitted_params = @parameters.keys - permitted_keys.flatten
  raise Zoom::ParameterNotPermitted, non_permitted_params.to_s unless non_permitted_params.empty?
end

#permit_value(key, values) ⇒ Object



64
65
66
67
68
69
# File 'lib/zoom/params.rb', line 64

def permit_value(key, values)
  value = @parameters[key]
  if !values.include?(value)
    raise Zoom::ParameterValueNotPermitted, "#{key}: #{value}"
  end
end

#require(*keys) ⇒ Object



14
15
16
17
18
# File 'lib/zoom/params.rb', line 14

def require(*keys)
  missing_keys = find_missing_keys(keys.flatten)
  return self.class.new(except(keys)) if missing_keys.empty?
  raise Zoom::ParameterMissing, missing_keys.to_s
end