Class: CleanParams::Configuration

Inherits:
Object
  • Object
show all
Defined in:
lib/clean_params.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

return nil if no rule for this attribute



62
63
64
# File 'lib/clean_params.rb', line 62

def method_missing(method, *args, &block)
  controller_params["#{method}"]
end

Instance Attribute Details

#controller_paramsObject

Returns the value of attribute controller_params.



23
24
25
# File 'lib/clean_params.rb', line 23

def controller_params
  @controller_params
end

#paramsObject

Returns the value of attribute params.



23
24
25
# File 'lib/clean_params.rb', line 23

def params
  @params
end

Instance Method Details

#extract_paramsObject

for each rule in configuration file, check the params hash and sets instance variables



26
27
28
29
30
# File 'lib/clean_params.rb', line 26

def extract_params
  params.each do |key, val|
    set_instances(key, val)
  end
end

#get_value_from_params(val, controllerParams) ⇒ Object

search params hash for values in rules



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

def get_value_from_params(val, controllerParams)
  paramVariations = val[0]
  defaultValue = val[1]
  if paramVariations.is_a? String
    paramVariations = paramVariations.split(",")
  end
  paramVariations.each do |param|
    answer = search_hash(controllerParams, param)
    return answer if answer
  end
  defaultValue # return default if no match
end

#search_hash(h, search) ⇒ Object

Utility method: search hash recursively



52
53
54
55
56
57
58
59
# File 'lib/clean_params.rb', line 52

def search_hash(h, search)
  return h[search] if h.fetch(search, nil)
  h.keys.each do |k|
    answer = search_hash(h[k], search) if h[k].is_a? Hash
    return answer if answer
  end
  nil
end

#set_instances(key, val) ⇒ Object



32
33
34
35
# File 'lib/clean_params.rb', line 32

def set_instances(key, val)
  self.class.send(:attr_accessor, key)
  instance_variable_set("@#{key}", get_value_from_params(val, controller_params))
end