Class: Tigon::HashTransformer

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

Instance Method Summary collapse

Constructor Details

#initialize(hash_or_value, options = {}) ⇒ HashTransformer

Returns a new instance of HashTransformer.



3
4
5
6
7
8
9
10
11
# File 'lib/tigon/hash_transformer.rb', line 3

def initialize(hash_or_value, options = {})
  @options = options
  @current_value = hash_or_value
  if @current_value.is_a?(Hash) && !options[:exclusive]
    @new_hash = @current_value
  else
    @new_hash = {}
  end
end

Instance Method Details

#furthest_value_from_hash(key_array, lookup_hash) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/tigon/hash_transformer.rb', line 67

def furthest_value_from_hash(key_array, lookup_hash)
  key_array.reduce(lookup_hash) do |context, k|
    if context.is_a?(Hash)
      context[k]
    else
      context
    end
  end
end

#keep(name) ⇒ Object



21
22
23
24
# File 'lib/tigon/hash_transformer.rb', line 21

def keep(name)
  @new_hash[name] = @current_value[name]
  @new_hash
end

#morph(name, newname = false, options = false, &blk) ⇒ Object



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/tigon/hash_transformer.rb', line 26

def morph(name, newname = false, options = false, &blk)
  options ||= @options

  replacement_key = if newname
    newname
  else
    if name.is_a?(String)
      name
    else
      name.last #assumes an array was passed
    end
  end

  if @current_value.is_a?(Hash) && (@current_value.key?(name) || (name.is_a?(Array) && @current_value.key?(name[0])))
    if name.is_a?(Array)
      current_val = furthest_value_from_hash(name, @current_value)
    else
      current_val = @current_value[name]
    end

    if block_given?
      @new_hash[replacement_key] = nest_tranformation(current_val, replacement_key, options, blk)
    else
      @new_hash[replacement_key] = current_val
    end
    @new_hash.delete(name) if newname
  end
  @new_hash
end

#nest_tranformation(val, replacement_key, options, blk) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/tigon/hash_transformer.rb', line 56

def nest_tranformation(val, replacement_key, options, blk)
    transformer = self.class.new(val, options)
    transformed_val = transformer.instance_exec(&blk)

    #preserve values from previous calls to morph
    if transformed_val.is_a?(Hash) && @new_hash[replacement_key]
      transformed_val = transformed_val.merge(@new_hash[replacement_key])
    end
    transformed_val
end

#new_hashObject



13
14
15
# File 'lib/tigon/hash_transformer.rb', line 13

def new_hash
  @new_hash
end

#valueObject



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

def value
  @current_value
end