Class: ActiveRecord::OnDemand::Result
- Includes:
- Enumerable
- Defined in:
- lib/ar-ondemand/on_demand.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#initialize(model, results, key_column, defaults) ⇒ Result
constructor
A new instance of Result.
Methods inherited from ResultSet
#each, #first, #ids, #last, #length
Constructor Details
#initialize(model, results, key_column, defaults) ⇒ Result
Returns a new instance of Result.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/ar-ondemand/on_demand.rb', line 10 def initialize(model, results, key_column, defaults) super(model, results) raise 'Key column cannot be blank.' if key_column.blank? raise 'Defaults cannot be empty.' if defaults.empty? @key_column = key_column.to_s @defaults = defaults @key_index = @col_indexes[@key_column] raise "Unknown index #{key_column}" if @key_index.nil? @has_any_assets = !ids.empty? || @model.unscoped.where(@defaults).exists? @new_params = @defaults.dup @new_params[@key_column.to_sym] = nil @results_to_hash = @results.rows.inject({}) do |h, row| raise "Duplicate key found for result set: #{row[@key_index]}" if h.has_key? row[@key_index] h[row[@key_index]] = row h end self end |
Instance Method Details
#[](key) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/ar-ondemand/on_demand.rb', line 34 def [](key) raise 'Search key cannot be blank.' if key.blank? rec = @results_to_hash[key] if rec.nil? rec = if @has_any_assets @model.unscoped .where(@defaults.merge(@key_column => key)) .first_or_initialize else @new_params[@key_column.to_sym] = key @model.new @new_params end unless rec.persisted? # These are not getting initialized for some reason, so set using what is passed in @defaults.each_pair do |k, v| next unless v.is_a?(::ActiveRecord::Base) meth = k.to_s next unless meth.end_with? '_id' rec.send("#{meth[0...-3]}=", v) end # This helps prevent a lookup into the db when we know there couldn't be any data yet @model.reflections.select { |_, v| v.macro == :has_and_belongs_to_many }.keys.each do |r| rec.send("#{r}=", []) end end rec else ::ActiveRecord::OnDemand::Record.new convert_to_hash(rec), @model, @defaults end end |