Class: Latinum::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/latinum/collection.rb

Overview

Aggregates a set of resources, typically used for summing values.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(names = Set.new) ⇒ Collection

Initialize the collection with a given set of resource names.



28
29
30
31
# File 'lib/latinum/collection.rb', line 28

def initialize(names = Set.new)
	@names = names
	@resources = Hash.new {|hash, key| @names << key; BigDecimal.new("0")}
end

Instance Attribute Details

#namesObject (readonly)

All resource names which have been added to the collection, e.g. ‘[’NZD’, ‘USD’]‘.



34
35
36
# File 'lib/latinum/collection.rb', line 34

def names
  @names
end

#resourcesObject (readonly)

A map of ‘name` => `total` for all added resources. Totals are stored as BigDecimal instances.



37
38
39
# File 'lib/latinum/collection.rb', line 37

def resources
  @resources
end

Instance Method Details

#<<(object) ⇒ Object

Add a resource, an array of resources, or another collection into this one.



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/latinum/collection.rb', line 45

def << object
	case object
	when Resource
		add(object)
	when Array
		object.each { |resource| add(resource) }
	when Collection
		object.resources.each { |name, amount| @resources[name] += amount }
	end
	
	return self
end

#[](key) ⇒ Object

Get a ‘Resource` for the given name:



59
60
61
# File 'lib/latinum/collection.rb', line 59

def [] key
	Resource.new(@resources[key], key)
end

#[]=(key, amount) ⇒ Object

Set a ‘BigDecimal` value for the given name:



64
65
66
# File 'lib/latinum/collection.rb', line 64

def []= key, amount
	@resources[key] = amount
end

#add(resource) ⇒ Object

Add a resource into the totals.



40
41
42
# File 'lib/latinum/collection.rb', line 40

def add resource
	@resources[resource.name] += resource.amount
end