Module: Usmu::Helpers::Indexer::ClassMethods

Defined in:
lib/usmu/helpers/indexer.rb

Instance Method Summary collapse

Instance Method Details

#indexer(variable) ⇒ void



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/usmu/helpers/indexer.rb', line 10

def indexer(variable)
  # An index accessor to directly access the configuration file. It should be noted that `['source']` and
  # `#source_path` and other similar pairs will have different values. `['source']` is the raw value from the
  # configuration file while the latter is a path on the system, potentially altered by the path from the current
  # working directory to the configuration file and other factors. The accessor functions such as `#source_path`
  # should be preferred for most usages.
  #
  # @param [String, Symbol] indices
  #   A list of indices to use to find the value to return. Can also include an options hash with the
  #   following options:
  #
  #   * `:default`: Sets the default value if the value can't be found.
  #
  # @return [Array, Hash, String, Symbol]
  #   Returns a value from the hash loaded from YAML. The type of value will ultimately depend on the configuration
  #   file and the indices provided.
  define_method(:[]) do |*indices|
    if indices.last.instance_of? Hash
      opts = indices.pop
    else
      opts = {}
    end

    value = variable.to_s[0] == '@' ? instance_variable_get(variable) : send(variable)
    while indices.length > 0
      i = indices.shift
      if value.key? i
        value = value[i]
      else
        return opts[:default]
      end
    end

    value
  end

  define_method(:key?) do |index|
    value = variable.to_s[0] == '@' ? instance_variable_get(variable) : send(variable)
    value.key? index
  end
end