Class: Bespoke::IndexedCollection
- Inherits:
-
Object
- Object
- Bespoke::IndexedCollection
- Defined in:
- lib/bespoke/indexed_collection.rb
Instance Attribute Summary collapse
-
#collections ⇒ Object
readonly
Returns the value of attribute collections.
Instance Method Summary collapse
- #add(collection_name, object) ⇒ Object
- #find(collection_name, key) ⇒ Object
- #index(collection_name, index_key_method = nil, &block) ⇒ Object
-
#initialize ⇒ IndexedCollection
constructor
A new instance of IndexedCollection.
- #proc_for_key(key) ⇒ Object
Constructor Details
#initialize ⇒ IndexedCollection
Returns a new instance of IndexedCollection.
7 8 9 10 |
# File 'lib/bespoke/indexed_collection.rb', line 7 def initialize @index_columns = {} @collections = {} end |
Instance Attribute Details
#collections ⇒ Object (readonly)
Returns the value of attribute collections.
5 6 7 |
# File 'lib/bespoke/indexed_collection.rb', line 5 def collections @collections end |
Instance Method Details
#add(collection_name, object) ⇒ Object
28 29 30 31 32 33 34 35 36 37 |
# File 'lib/bespoke/indexed_collection.rb', line 28 def add(collection_name, object) col_sym = collection_name.to_sym key_from_object = @index_columns[col_sym] key = key_from_object.call(object) begin @collections[col_sym][key] = object rescue NoMethodError raise "Can't find collection #{col_sym} with key #{key}" end end |
#find(collection_name, key) ⇒ Object
39 40 41 42 43 |
# File 'lib/bespoke/indexed_collection.rb', line 39 def find(collection_name, key) if collection = @collections[collection_name.to_sym] collection[key] end end |
#index(collection_name, index_key_method = nil, &block) ⇒ Object
22 23 24 25 26 |
# File 'lib/bespoke/indexed_collection.rb', line 22 def index(collection_name, index_key_method=nil, &block) col_sym = collection_name.to_sym @index_columns[col_sym] = block || proc_for_key(index_key_method) @collections[col_sym] = {} end |
#proc_for_key(key) ⇒ Object
12 13 14 15 16 17 18 19 20 |
# File 'lib/bespoke/indexed_collection.rb', line 12 def proc_for_key(key) return Proc.new{ |x| nil } unless key key = key.first if key.is_a?(Array) and key.size == 1 if key.is_a?(Array) Proc.new{ |x| key.map{ |k| (x[k] rescue x.send(k)) } } else Proc.new{ |x| (x[key] rescue x.send(key)) } end end |