Class: Inspec::Attribute

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

Defined Under Namespace

Classes: Error, RequiredError, TypeError, ValidationError

Constant Summary collapse

VALID_TYPES =
%w{
  String
  Numeric
  Regexp
  Array
  Hash
  Boolean
  Any
}.freeze
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.



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

def initialize(name, options = {})
  @name = name
  @opts = options
  validate_value_type(default) if @opts.key?(:type) && @opts.key?(:default)
  @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

Instance Method Details

#descriptionObject



61
62
63
# File 'lib/inspec/objects/attribute.rb', line 61

def description
  @opts[:description]
end

#ruby_var_identifierObject



65
66
67
# File 'lib/inspec/objects/attribute.rb', line 65

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

#titleObject



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

def title
  @opts[:title]
end

#to_hashObject



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

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

#to_rubyObject



76
77
78
79
80
81
82
83
# File 'lib/inspec/objects/attribute.rb', line 76

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



85
86
87
# File 'lib/inspec/objects/attribute.rb', line 85

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

#valueObject



48
49
50
51
52
53
54
55
# File 'lib/inspec/objects/attribute.rb', line 48

def value
  if @value.nil?
    validate_required(@value) if @opts[:required] == true
    @value = default
  else
    @value
  end
end

#value=(new_value) ⇒ Object



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

def value=(new_value)
  validate_value_type(new_value) if @opts.key?(:type)
  @value = new_value
end