class RemoteRecord::Collection
Wraps operations on collections of remote references. By calling remote on on an ActiveRecord relation, you'll get a RemoteRecord::Collection
you can use to more easily fetch multiple records at once.
The default implementation is naive and sends a request per object.
Public Class Methods
new(active_record_relation, config = nil, id: :remote_resource_id)
click to toggle source
# File lib/remote_record/collection.rb, line 12 def initialize(active_record_relation, config = nil, id: :remote_resource_id) @relation = active_record_relation @config = config @id_field = id end
Public Instance Methods
all()
click to toggle source
# File lib/remote_record/collection.rb, line 18 def all fetch_all_scoped_records(@relation) end
where()
click to toggle source
# File lib/remote_record/collection.rb, line 22 def where raise NotImplementedError.new, "Implement #where on #{self.class.name} to filter records using the API." end
Private Instance Methods
fetch_all_scoped_records(relation)
click to toggle source
Override this to define more succinct ways to request all records at once. If your API has a search endpoint, you may want to use that. Otherwise, list all objects and leave it to Remote Record to pick out the ones you have in your database.
# File lib/remote_record/collection.rb, line 33 def fetch_all_scoped_records(relation) relation.map do |record| record.remote.remote_record_config.merge!(@config) record.tap { |r| r.remote.fresh } end end
match_remote_resources(response) { |resource| ... }
click to toggle source
# File lib/remote_record/collection.rb, line 40 def match_remote_resources(response) @relation.map do |record| prefetched_record = response.find do |resource| yield(resource).to_s == record.public_send(@id_field).remote_resource_id end next nil unless prefetched_record.present? record.remote.attrs = prefetched_record record end.compact end
match_remote_resources_by_id(response)
click to toggle source
# File lib/remote_record/collection.rb, line 52 def match_remote_resources_by_id(response) match_remote_resources(response) { |resource| resource['id'] } end