Class: Blocks::HashWithCaller

Inherits:
HashWithIndifferentAccess
  • Object
show all
Defined in:
lib/blocks/utilities/hash_with_caller.rb

Direct Known Subclasses

HashWithRenderStrategy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ HashWithCaller

Returns a new instance of HashWithCaller.



5
6
7
8
9
10
# File 'lib/blocks/utilities/hash_with_caller.rb', line 5

def initialize(*args)
  self.callers = HashWithIndifferentAccess.new
  options = args.extract_options!
  add_options(args.first, options)
  super &nil
end

Instance Attribute Details

#callersObject

Returns the value of attribute callers.



3
4
5
# File 'lib/blocks/utilities/hash_with_caller.rb', line 3

def callers
  @callers
end

Instance Method Details

#add_options(*args) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/blocks/utilities/hash_with_caller.rb', line 33

def add_options(*args)
  options = args.extract_options!

  caller_id = args.first.to_s.presence || ""

  if !options.is_a?(HashWithCaller) && Blocks.lookup_caller_location?
    caller_location = caller.detect do |c|
      !c.include?("/lib/blocks") &&
      !c.include?("/lib/ruby") &&
      !c.include?("patch")
    end.try(:split, ":in").try(:[], 0)

    caller_id += " from #{caller_location}" if caller_location
  end

  options.each do |key, value|
    current_value = self[key]

    if options.is_a?(HashWithCaller)
      setter = options.callers[key]
    else
      setter = "set by #{caller_id}"
    end

    if !self.key?(key)
      self[key] = value
      callers[key] = setter

    elsif current_value.is_a?(Hash) && value.is_a?(Hash)
      self[key] = value.deep_merge(current_value)
      callers[key] = "#{callers[key]}, #{setter}"
      # TODO: handle attribute merges here
    end
  end
end

#nested_under_indifferent_accessObject



69
70
71
# File 'lib/blocks/utilities/hash_with_caller.rb', line 69

def nested_under_indifferent_access
  self
end

#to_sObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/blocks/utilities/hash_with_caller.rb', line 12

def to_s
  description = []

  description << "{"
  description << map do |key, value|
    value_display = case value
    when Symbol
      ":#{value}"
    when String
      "\"#{value}\""
    when Proc
      "Proc"
    else
      value
    end
    "\"#{key}\" => #{value_display}, # [#{callers[key]}]"
  end.join(",\n")
  description << "}"
  description.join("\n")
end