Class: OctofactsUpdater::Fact

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value) ⇒ Fact

Constructor.

name - The String naming the fact. value - The arbitrary object with the value of the fact.



15
16
17
18
# File 'lib/octofacts_updater/fact.rb', line 15

def initialize(name, value)
  @name = name
  @value = value
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



9
10
11
# File 'lib/octofacts_updater/fact.rb', line 9

def name
  @name
end

Instance Method Details

#set_value(new_value, name_in = nil) ⇒ Object

Set the value of the fact. If the name is specified, this will dig into a structured fact to set the value within the structure.

new_value - An object with the new value for the fact

name_in - An optional String to dig into the structure (formatted with

indicating hash delimiters)



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/octofacts_updater/fact.rb', line 58

def set_value(new_value, name_in = nil)
  if name_in.nil?
    if new_value.is_a?(Proc)
      return @value = new_value.call(@value)
    end

    return @value = new_value
  end

  parts = if name_in.is_a?(String)
    name_in.split("::")
  elsif name_in.is_a?(Array)
    name_in.map do |item|
      if item.is_a?(String)
        item
      elsif item.is_a?(Hash) && item.key?("regexp")
        Regexp.new(item["regexp"])
      else
        raise ArgumentError, "Unable to interpret structure item: #{item.inspect}"
      end
    end
  else
    raise ArgumentError, "Unable to interpret structure: #{name_in.inspect}"
  end

  set_structured_value(@value, parts, new_value)
end

#value(name_in = nil) ⇒ Object

Get the value of the fact. If the name is specified, this will dig into a structured fact to pull out the value within the structure.

name_in - An optional String to dig into the structure (formatted with

indicating hash delimiters)

Returns the value of the fact.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/octofacts_updater/fact.rb', line 26

def value(name_in = nil)
  # Just a normal lookup -- return the value
  return @value if name_in.nil?

  # Structured lookup returns nil unless the fact is actually structured.
  return unless @value.is_a?(Hash)

  # Dig into the hash to pull out the desired value.
  pointer = @value
  parts = name_in.split("::")
  last_part = parts.pop

  parts.each do |part|
    return unless pointer[part].is_a?(Hash)
    pointer = pointer[part]
  end

  pointer[last_part]
end

#value=(new_value) ⇒ Object

Set the value of the fact.

new_value - An object with the new value for the fact



49
50
51
# File 'lib/octofacts_updater/fact.rb', line 49

def value=(new_value)
  set_value(new_value)
end