Class: Inspec::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/objects/attribute.rb

Constant Summary collapse

DEFAULT_ATTRIBUTE =
Class.new do
  def initialize(name)
    @name = name
  end

  def method_missing(*_)
    Inspec::Log.warn(
      "Returning DEFAULT_ATTRIBUTE for '#{@name}'. "\
      "Use --attrs to provide a value for '#{@name}' or specify a default  "\
      "value with `attribute('#{@name}', default: 'somedefault', ...)`.",
    )

    self
  end

  def respond_to_missing?(_, _)
    true
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



28
29
30
31
32
# File 'lib/inspec/objects/attribute.rb', line 28

def initialize(name, options = {})
  @name = name
  @opts = options
  @value = nil
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



5
6
7
# File 'lib/inspec/objects/attribute.rb', line 5

def name
  @name
end

#valueObject

implicit call is done by inspec to determine the value of an attribute



35
36
37
# File 'lib/inspec/objects/attribute.rb', line 35

def value
  @value.nil? ? default : @value
end

Instance Method Details

#defaultObject



39
40
41
# File 'lib/inspec/objects/attribute.rb', line 39

def default
  @opts.key?(:default) ? @opts[:default] : DEFAULT_ATTRIBUTE.new(@name)
end

#descriptionObject



47
48
49
# File 'lib/inspec/objects/attribute.rb', line 47

def description
  @opts[:description]
end

#ruby_var_identifierObject



51
52
53
# File 'lib/inspec/objects/attribute.rb', line 51

def ruby_var_identifier
  @opts[:identifier] || 'attr_' + @name.downcase.strip.gsub(/\s+/, '-').gsub(/[^\w-]/, '')
end

#titleObject



43
44
45
# File 'lib/inspec/objects/attribute.rb', line 43

def title
  @opts[:title]
end

#to_hashObject



55
56
57
58
59
60
# File 'lib/inspec/objects/attribute.rb', line 55

def to_hash
  {
    name: @name,
    options: @opts,
  }
end

#to_rubyObject



62
63
64
65
66
67
68
69
# File 'lib/inspec/objects/attribute.rb', line 62

def to_ruby
  res = ["#{ruby_var_identifier} = attribute('#{@name}',{"]
  res.push "  title: '#{title}'," unless title.to_s.empty?
  res.push "  default: #{default.inspect}," unless default.to_s.empty?
  res.push "  description: '#{description}'," unless description.to_s.empty?
  res.push '})'
  res.join("\n")
end

#to_sObject



71
72
73
# File 'lib/inspec/objects/attribute.rb', line 71

def to_s
  "Attribute #{@name} with #{@value}"
end