Class: ChemistryKit::Chemist::Repository::CsvChemistRepository
- Inherits:
-
Object
- Object
- ChemistryKit::Chemist::Repository::CsvChemistRepository
- Defined in:
- lib/chemistrykit/chemist/repository/csv_chemist_repository.rb
Overview
Provides the ability to load a chemist by type identifyer from a csv file
Instance Method Summary collapse
-
#initialize(csv_path) ⇒ CsvChemistRepository
constructor
A new instance of CsvChemistRepository.
-
#load_chemist_by_key(key) ⇒ Object
Required Method Load a specific chemist by the unique key.
-
#load_first_chemist_of_type(type) ⇒ Object
Required Method Load the first chemist found for a given type.
-
#load_random_chemist_of_type(type) ⇒ Object
Required Method Loads a chemist at random from all those found with a given type.
Constructor Details
#initialize(csv_path) ⇒ CsvChemistRepository
Returns a new instance of CsvChemistRepository.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/chemistrykit/chemist/repository/csv_chemist_repository.rb', line 14 def initialize(csv_path) @tables = [] @chemist_cache = {} files = csv_path.kind_of?(String) ? [csv_path] : csv_path files.each do |file| raise ArgumentError, 'Supplied file does not exist!' unless File.exist? file table = CSV.read(file, { headers: true, converters: :all, header_converters: :symbol }) [:key, :type].each do |header| unless table.headers.include?(header) || table.headers.length == 0 raise ArgumentError, "You must define a #{header.to_s} field!" end end @tables.push table end end |
Instance Method Details
#load_chemist_by_key(key) ⇒ Object
Required Method Load a specific chemist by the unique key
33 34 35 36 37 38 39 40 |
# File 'lib/chemistrykit/chemist/repository/csv_chemist_repository.rb', line 33 def load_chemist_by_key(key) @tables.each do |table| chemist_data = table.find { |row| row[:key] == key } chemist = make_chemist(key, chemist_data[:type], chemist_data) if chemist_data return fetch_from_cache(chemist) if chemist end raise ArgumentError, "Chemist for type \"#{key}\" not found!" end |
#load_first_chemist_of_type(type) ⇒ Object
Required Method Load the first chemist found for a given type
44 45 46 |
# File 'lib/chemistrykit/chemist/repository/csv_chemist_repository.rb', line 44 def load_first_chemist_of_type(type) fetch_from_cache(load_chemists_of_type(type)[0]) end |
#load_random_chemist_of_type(type) ⇒ Object
Required Method Loads a chemist at random from all those found with a given type
50 51 52 |
# File 'lib/chemistrykit/chemist/repository/csv_chemist_repository.rb', line 50 def load_random_chemist_of_type(type) fetch_from_cache(load_chemists_of_type(type).sample) end |