Class: FlexiRecord::RecordArray
- Inherits:
-
Array
- Object
- Array
- FlexiRecord::RecordArray
- Defined in:
- lib/flexirecord.rb
Overview
Sub-class of Array to provide special methods to be used on multiple database records at once.
Instance Method Summary collapse
-
#initialize(record_class, *arguments) ⇒ RecordArray
constructor
Creates a new Array to hold objects of type ‘record_class’.
-
#preload(attr, *arguments) ⇒ Object
Preloads the attribute named ‘attr’ in each record of the RecordArray, without doing one SQL query for each record.
-
#record_class ⇒ Object
Returns the record class of the elements of the array.
-
#reselect(sql_snippet = nil, *arguments) ⇒ Object
Returns a RecordArray of re-selected objects.
Constructor Details
#initialize(record_class, *arguments) ⇒ RecordArray
Creates a new Array to hold objects of type ‘record_class’. Additional arguments will be passed to Array#new.
473 474 475 476 477 |
# File 'lib/flexirecord.rb', line 473 def initialize(record_class, *arguments) super(*arguments) @flexirecord_class = record_class @flexirecord_preloaded = {} end |
Instance Method Details
#preload(attr, *arguments) ⇒ Object
Preloads the attribute named ‘attr’ in each record of the RecordArray, without doing one SQL query for each record. Can return another RecordArray, which can be used for the next level of preloading.
485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'lib/flexirecord.rb', line 485 def preload(attr, *arguments) attr = attr.to_s @flexirecord_class.prepare_read_parameters(attr, arguments) cache_key = [attr] + arguments if @flexirecord_preloaded.has_key?(cache_key) return @flexirecord_preloaded[cache_key] end attr = attr.to_s loader = self.record_class.loader(attr) unless loader raise ArgumentError, "Could not preload attribute '#{attr}', due to missing loading procedure." end return @flexirecord_preloaded[cache_key] = loader.call(self, arguments) end |
#record_class ⇒ Object
Returns the record class of the elements of the array.
480 481 482 |
# File 'lib/flexirecord.rb', line 480 def record_class @flexirecord_class end |
#reselect(sql_snippet = nil, *arguments) ⇒ Object
Returns a RecordArray of re-selected objects. This can be used to re-sort records by the database, to do further filtering, or to reload all records at once.
501 502 503 504 505 506 |
# File 'lib/flexirecord.rb', line 501 def reselect(sql_snippet=nil, *arguments) unless self.empty? @flexirecord_class.select_by_value_set(@flexirecord_class.primary_columns, self.collect { |record| @flexirecord_class.primary_columns.collect { |column| record.read(column) } }, sql_snippet, *arguments) end return self end |