Class: Moonrope::ParamSet

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

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ ParamSet

Initialize a new ParamSet

Parameters:

  • params (Hash or String) (defaults to: {})

    the initial params. If string, will be parsed through JSON.



9
10
11
12
# File 'lib/moonrope/param_set.rb', line 9

def initialize(params = {})
  @params = (params.is_a?(String) ? JSON.parse(params) : params) || {}
  @defaults = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missingObject

Return the value for the given key

Parameters:

  • key (String)

    the key to lookup

Returns:

  • (Object)

    the value



40
41
42
43
44
45
46
47
# File 'lib/moonrope/param_set.rb', line 40

def _value_for(key)
  # Get the value from the params and defaults
  value = @params.has_key?(key.to_s) ? @params[key.to_s] : @defaults[key.to_s]
  # Ensure that empty strings are actually nil.
  value = nil if value.is_a?(String) && value.length == 0
  # Return the value
  value
end

Instance Method Details

#_as_hashObject

Return the params as a ruby hash



17
18
19
20
21
22
# File 'lib/moonrope/param_set.rb', line 17

def _as_hash
  @defaults.merge(@params).inject({}) do |hash, (k, v)|
    hash[k.to_s] = v
    hash
  end
end

#_defaults=(defaults) ⇒ void

This method returns an undefined value.

Set the defaults for the param set

Parameters:

  • defaults (Hash)


57
58
59
60
61
# File 'lib/moonrope/param_set.rb', line 57

def _defaults=(defaults)
  if defaults.is_a?(Hash)
    @defaults = defaults
  end
end

#_set_value(name, value) ⇒ Object

Set the value for a given param

Parameters:

  • key (String)
  • value (AnyObject)


48
49
50
# File 'lib/moonrope/param_set.rb', line 48

def _set_value(name, value)
  @params[name.to_s] = value
end

#_value_for(key) ⇒ Object Also known as: [], method_missing

Return the value for the given key

Parameters:

  • key (String)

    the key to lookup

Returns:

  • (Object)

    the value



30
31
32
33
34
35
36
37
# File 'lib/moonrope/param_set.rb', line 30

def _value_for(key)
  # Get the value from the params and defaults
  value = @params.has_key?(key.to_s) ? @params[key.to_s] : @defaults[key.to_s]
  # Ensure that empty strings are actually nil.
  value = nil if value.is_a?(String) && value.length == 0
  # Return the value
  value
end

#has?(key) ⇒ Boolean

Does the specified key exist?

Parameters:

  • key (Symbol or String)

Returns:

  • (Boolean)


69
70
71
# File 'lib/moonrope/param_set.rb', line 69

def has?(key)
  @params.keys.include?(key.to_s) || @defaults.keys.include?(key.to_s)
end