Class: BjnInventory::Inventory::Source

Inherits:
Object
  • Object
show all
Defined in:
lib/bjn_inventory/inventory/source.rb

Overview

The BjnInventory::Inventory::Source describes a source of inventory data: at its heart, a list (array) of entries, each of which is a hash, in the source’s “native” schema.

Instance Method Summary collapse

Constructor Details

#initialize(spec = { entries: { } }) ⇒ Source

Create new instance with the entries supplied (or fetch the entries from the specified source. The constructor accepts the following keyword arguments:

Parameters:

  • spec (defaults to: { entries: { } })

    :file A JSON-formatted file containing a JSON array to read entries from

  • spec (defaults to: { entries: { } })

    :entries Directly-specified inventory source entries

  • spec (defaults to: { entries: { } })

    :rules A rules specification (either a file or a text)



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/bjn_inventory/inventory/source.rb', line 18

def initialize(spec={ entries: { } })
    spec = spec.stringify_keys
    @context = spec.delete('context')
    @model = spec.delete('model')
    @rules = spec.delete('rules')
    @devices = nil
    @logger = spec.delete('logger') || BjnInventory::DefaultLogger.new
    @spec = spec
    source_type = spec.keys.first
    case source_type
    when 'entries'
        @entries = spec[source_type]
    when 'file'
        @entries = JSON.parse(File.read(spec[source_type]))
    else
        raise ArgumentError.new("Unimplemented inventory source '#{source_type}'")
    end
end

Instance Method Details

#devices(kwargs = {}) ⇒ Object

Return a list of model-standardized device hashes

Parameters:

  • kwargs (defaults to: {})

    :context Context data to be used when applying mapping rules

  • kwargs (defaults to: {})

    :model The device model to be used. If not specified, the BjnInventory::Device default model is used.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bjn_inventory/inventory/source.rb', line 41

def devices(kwargs={})
    if @devices
        @devices
    else
        BjnInventory::Device.use_context(@context)
        BjnInventory::Device.use_model(@model)

        @logger.debug("Creating device list from #{@spec}")
        device_prototype = BjnInventory::Device.using(@rules)
        @devices = BjnInventory::List.new(@entries.map do |entry|
            begin
                device_prototype.new(entry).validate
            rescue Exception => err
                @logger.error "#{err.class}: #{err.message}"
                nil
            end
        end.reject { |entry| entry.nil? })
        @devices
    end
end