Module: Widgeo::Collection

Included in:
Continent, Territory
Defined in:
lib/widgeo/collection.rb

Overview

Methods for working with collection of entities

Instance Method Summary collapse

Instance Method Details

#allObject

Parse full list and memoize it



39
40
41
# File 'lib/widgeo/collection.rb', line 39

def all
  @all ||= dataset.map { |item| new item }
end

#datasetObject

Return the dataset



12
13
14
15
16
17
18
19
# File 'lib/widgeo/collection.rb', line 12

def dataset
  # Raise an exception if the dataset file has not been set on the class
  raise UndefinedDatasetError unless dataset_file

  @dataset ||= YAML.load_file(
    File.join(File.dirname(__FILE__), '../', 'data', "#{dataset_file}.yml")
  )
end

#dataset_file(file_name = nil) ⇒ Object

Set/Get the dataset file name



7
8
9
# File 'lib/widgeo/collection.rb', line 7

def dataset_file(file_name = nil)
  @dataset_file ||= file_name
end

#filter_by(attributes) ⇒ Object

Filter the items by a combination of values



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

def filter_by(attributes)
  all.select { |item| matches? item, attributes }
end

#find_by(attribute, value) ⇒ Object

Find an item by an attribute



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

def find_by(attribute, value)
  all.detect { |continent| continent.send(attribute) == value }
end

#matches?(item, attributes) ⇒ Boolean

Does the item match the requested attributes?

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/widgeo/collection.rb', line 22

def matches?(item, attributes)
  attributes.map do |attribute, value|
    item.send(attribute) == value
  end.flatten == [true]
end