Class: HasharayExt::Logic

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, strict: true, separator: ".", default: nil) ⇒ Logic

Returns a new instance of Logic.



19
20
21
22
23
24
# File 'lib/hasharay_ext.rb', line 19

def initialize(data, strict: true, separator: ".", default: nil)
  @data = data
  @strict = strict
  @separator = separator
  @default = default
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



17
18
19
# File 'lib/hasharay_ext.rb', line 17

def data
  @data
end

#defaultObject (readonly)

Returns the value of attribute default.



17
18
19
# File 'lib/hasharay_ext.rb', line 17

def default
  @default
end

#separatorObject (readonly)

Returns the value of attribute separator.



17
18
19
# File 'lib/hasharay_ext.rb', line 17

def separator
  @separator
end

#strictObject (readonly)

Returns the value of attribute strict.



17
18
19
# File 'lib/hasharay_ext.rb', line 17

def strict
  @strict
end

Instance Method Details

#get(path) ⇒ Object

Raises:

  • (ArgumentError)


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
51
52
53
54
# File 'lib/hasharay_ext.rb', line 26

def get(path)
  raise ArgumentError.new("Not specified key") if path.blank?

  object = data.clone
  tree = path.split(separator)

  tree.each_with_index do |raw, index|
    raise ArgumentError.new("Not specified key") if raw.blank?

    keywords = raw.split("+")
    if index == (tree.size - 1) && keywords.size > 1
      # last iteration
      case object
      when Array
        return keywords.map do |keyword|
          fetch(object, keyword)
        end.transpose
      when Hash
        return keywords.each_with_object({}) { |e, res|
                 res[e] = fetch(object, e)
               }
      end
    else
      # every key
      object = fetch(object, raw)
    end
  end
  object
end