Class: Grimoire::System

Inherits:
Object
  • Object
show all
Defined in:
lib/grimoire/system.rb

Overview

Contains all available Units

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*_) ⇒ self

Create new system



13
14
15
# File 'lib/grimoire/system.rb', line 13

def initialize(*_)
  @units = Smash.new
end

Instance Attribute Details

#unitsSmash (readonly)

Returns:

  • (Smash)


8
9
10
# File 'lib/grimoire/system.rb', line 8

def units
  @units
end

Instance Method Details

#add_unit(*unit) ⇒ self

Register new unit

Parameters:

Returns:

  • (self)


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/grimoire/system.rb', line 21

def add_unit(*unit)
  if(bad_u = unit.flatten.detect{|u| !u.is_a?(Unit)})
    raise TypeError.new "Expecting `Unit` instance but received `#{bad_u.class}`"
  end
  [unit].flatten.compact.each do |u|
    unless(units[u.name])
      units[u.name] = []
    end
    units[u.name].push(u) unless units[u.name].include?(u)
  end
  self
end

#inspectString

Returns:

  • (String)


92
93
94
95
96
97
# File 'lib/grimoire/system.rb', line 92

def inspect
  "<#{self.class}:#{self.object_id}>: " <<
    units.to_a.sort_by(&:first).map do |name, units|
    "#{name}: #{units.map(&:version).sort.map(&:to_s).join(', ')}"
  end.join("\n")
end

#remove_unit(unit) ⇒ self

Remove registered unit

Parameters:

Returns:

  • (self)


39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/grimoire/system.rb', line 39

def remove_unit(unit)
  unless(unit.is_a?(Unit))
    raise TypeError.new "Expecting `Unit` instance but received `#{unit.class}`"
  end
  if(units[unit.name])
    units[unit.name].delete(unit)
    if(units[unit.name].empty?)
      units.delete(unit.name)
    end
  end
  self
end

#scrub!self

Removes any duplicate units registered and sorts all unit lists

Returns:

  • (self)


75
76
77
78
79
80
81
# File 'lib/grimoire/system.rb', line 75

def scrub!
  units.values.map do |items|
    items.sort!{|x,y| y.version <=> x.version}
    items.uniq!
  end
  self
end

#subset(unit_name, constraint) ⇒ Array<Unit>

Provide all available units that satisfy the constraint

Parameters:

Returns:



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/grimoire/system.rb', line 57

def subset(unit_name, constraint)
  unless(constraint.respond_to?(:requirements))
    raise TypeError.new "Expecting `#{REQUIREMENT_CLASS}` but received `#{constraint.class}`"
  end
  unless(units[unit_name])
    Grimoire.debug "Failed to locate any units loaded in system with requested name: `#{unit_name}`"
    []
  else
    units[unit_name].find_all do |unit|
      constraint.satisfied_by?(unit.version)
    end
  end
end

#to_json(*args) ⇒ String

Returns:

  • (String)


84
85
86
87
88
89
# File 'lib/grimoire/system.rb', line 84

def to_json(*args)
  MultiJson.dump(
    Smash.new(:units => units),
    *args
  )
end