Class: ActiveFedora::Associations::CollectionAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/active_fedora/associations/collection_association.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Attributes inherited from Association

#inversed, #owner, #reflection, #target

Instance Method Summary collapse

Methods inherited from Association

#association_scope, #initialize_attributes, #loaded!, #loaded?, #reload, #set_inverse_instance, #stale_target?, #target_scope

Constructor Details

#initialize(owner, reflection) ⇒ CollectionAssociation

Returns a new instance of CollectionAssociation



6
7
8
9
# File 'lib/active_fedora/associations/collection_association.rb', line 6

def initialize(owner, reflection)
  super
  construct_query
end

Instance Attribute Details

#proxyObject (readonly)

Returns the value of attribute proxy



4
5
6
# File 'lib/active_fedora/associations/collection_association.rb', line 4

def proxy
  @proxy
end

Instance Method Details

#add_to_target(record, skip_callbacks = false) {|record| ... } ⇒ Object

Yields:

  • (record)


300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/active_fedora/associations/collection_association.rb', line 300

def add_to_target(record, skip_callbacks = false)
#  transaction do
    callback(:before_add, record) unless skip_callbacks
    yield(record) if block_given?

    if @reflection.options[:uniq] && index = @target.index(record)
      @target[index] = record
    else
      @target << record
    end

    callback(:after_add, record) unless skip_callbacks
    set_inverse_instance(record)
 # end

  record
end

#any?Boolean

Returns:

  • (Boolean)


130
131
132
133
134
135
136
# File 'lib/active_fedora/associations/collection_association.rb', line 130

def any?
  if block_given?
    load_target.any? { |*block_args| yield(*block_args) }
  else
    !empty?
  end
end

#build(attributes = {}, &block) ⇒ Object



143
144
145
146
147
148
149
150
151
# File 'lib/active_fedora/associations/collection_association.rb', line 143

def build(attributes = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, &block) }
  else
    add_to_target(build_record(attributes)) do |record|
      yield(record) if block_given?
    end
  end
end

#concat(*records) ⇒ Object

Add records to this association. Returns self so method calls may be chained. Since << flattens its argument list and inserts each record, push and concat behave identically.



155
156
157
158
# File 'lib/active_fedora/associations/collection_association.rb', line 155

def concat(*records)
  load_target unless owner.new_record?
  concat_records(records)
end

#concat_records(*records) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/active_fedora/associations/collection_association.rb', line 160

def concat_records(*records)
  result = true

  records.flatten.each do |record|
    raise_on_type_mismatch(record)
    add_to_target(record) do |r|
      result &&= insert_record(record) unless owner.new_record?
    end
  end

  result && records
end

#count(options = {}) ⇒ Object

Count all records using solr. Construct options and pass them with scope to the target class's count.



235
236
237
# File 'lib/active_fedora/associations/collection_association.rb', line 235

def count(options = {})
  @reflection.klass.count(:conditions => @counter_query)
end

#create(attrs = {}) ⇒ Object



215
216
217
218
219
220
221
222
223
224
# File 'lib/active_fedora/associations/collection_association.rb', line 215

def create(attrs = {})
  if attrs.is_a?(Array)
    attrs.collect { |attr| create(attr) }
  else
    create_record(attrs) do |record|
      yield(record) if block_given?
      record.save
    end
  end
end

#create!(attrs = {}) ⇒ Object



226
227
228
229
230
231
# File 'lib/active_fedora/associations/collection_association.rb', line 226

def create!(attrs = {})
  create_record(attrs) do |record|
    yield(record) if block_given?
    record.save!
  end
end

#delete(*records) ⇒ Object

Removes records from this association calling before_remove and after_remove callbacks.

This method is abstract in the sense that delete_records has to be provided by descendants. Note this method does not imply the records are actually removed from the database, that depends precisely on delete_records. They are in any case removed from the collection.



201
202
203
# File 'lib/active_fedora/associations/collection_association.rb', line 201

def delete(*records)
  delete_or_destroy(records, options[:dependent])
end

#delete_allObject

Remove all records from this association

See delete for more info.



176
177
178
179
180
181
182
# File 'lib/active_fedora/associations/collection_association.rb', line 176

def delete_all
  # TODO load_target causes extra loads. Can't we just send delete requests?
  delete(load_target).tap do
    reset
    loaded!
  end
end

#destroy(*records) ⇒ Object

Destroy records and remove them from this association calling before_remove and after_remove callbacks.

Note that this method will always remove records from the database ignoring the :dependent option.



210
211
212
213
# File 'lib/active_fedora/associations/collection_association.rb', line 210

def destroy(*records)
  records = find(records) if records.any? { |record| record.kind_of?(Fixnum) || record.kind_of?(String) }
  delete_or_destroy(records, :destroy)
end

#destroy_allObject

Remove all records from this association

See delete for more info.



187
188
189
190
191
192
# File 'lib/active_fedora/associations/collection_association.rb', line 187

def destroy_all
  destroy(load_target).tap do
    reset
    loaded!
  end
end

#empty?Boolean

Returns true if the collection is empty.

If the collection has been loaded it is equivalent to collection. size.zero?. If the collection has not been loaded, it is equivalent to collection.count_records == 0. If the collection has not already been loaded and you are going to fetch the records anyway it is better to check collection.length.zero?.

Returns:

  • (Boolean)


97
98
99
100
101
102
103
# File 'lib/active_fedora/associations/collection_association.rb', line 97

def empty?
  if loaded?
    size.zero?
  else
    @target.blank? && count_records == 0
  end
end

#find(*args) ⇒ Object



59
60
61
# File 'lib/active_fedora/associations/collection_association.rb', line 59

def find(*args)
  scope.find(*args)
end

#find_targetObject



263
264
265
266
267
268
269
# File 'lib/active_fedora/associations/collection_association.rb', line 263

def find_target
  # TODO: don't reify, just store the solr results and lazily reify.
  # For now, we set a hard limit of 1000 results.
  records = ActiveFedora::QueryResultBuilder.reify_solr_results(load_from_solr(rows: 1000))
  records.each { |record| set_inverse_instance(record) }
  records
end

#first(*args) ⇒ Object



63
64
65
# File 'lib/active_fedora/associations/collection_association.rb', line 63

def first(*args)
  first_or_last(:first, *args)
end

#ids_readerObject

Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/active_fedora/associations/collection_association.rb', line 33

def ids_reader
  if loaded?
    load_target.map do |record|
      record.id
    end
  else
    load_from_solr.map do |solr_record|
      solr_record['id']
    end
  end
end

#ids_writer(ids) ⇒ Object

Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items



46
47
48
49
50
51
52
# File 'lib/active_fedora/associations/collection_association.rb', line 46

def ids_writer(ids)
  ids = Array(ids).reject { |id| id.blank? }
  replace(klass.find(ids))#.index_by { |r| r.id }.values_at(*ids))
  #TODO, like this when find() can return multiple records
  #send("#{reflection.name}=", reflection.klass.find(ids))
  #send("#{reflection.name}=", ids.collect { |id| reflection.klass.find(id)})
end

#include?(record) ⇒ Boolean

Returns:

  • (Boolean)


118
119
120
121
122
123
124
125
126
127
128
# File 'lib/active_fedora/associations/collection_association.rb', line 118

def include?(record)
  if record.is_a?(reflection.klass)
    if record.new_record?
      target.include?(record)
    else
      loaded? ? target.include?(record) : scope.exists?(record)
    end
  else
    false
  end
end

#last(*args) ⇒ Object



67
68
69
# File 'lib/active_fedora/associations/collection_association.rb', line 67

def last(*args)
  first_or_last(:last, *args)
end

#load_from_solr(opts = Hash.new) ⇒ Object

Parameters:

  • opts (Hash) (defaults to: Hash.new)

    Options that will be passed through to ActiveFedora::SolrService.query.



293
294
295
296
297
298
# File 'lib/active_fedora/associations/collection_association.rb', line 293

def load_from_solr(opts = Hash.new)
  return [] if @finder_query.empty?
  rows = opts.delete(:rows) { count }
  return [] if rows == 0
  SolrService.query(@finder_query, {rows: rows}.merge(opts))
end

#load_targetObject



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/active_fedora/associations/collection_association.rb', line 245

def load_target
  if find_target?
    targets = []

    begin
      targets = find_target
    rescue ObjectNotFoundError, Ldp::Gone => e
      ActiveFedora::Base.logger.error "Solr and Fedora may be out of sync:\n" + e.message if ActiveFedora::Base.logger
      reset
    end

    @target = merge_target_lists(targets, @target)
  end

  loaded!
  target
end

#merge_target_lists(loaded, existing) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/active_fedora/associations/collection_association.rb', line 271

def merge_target_lists(loaded, existing)
  return loaded if existing.empty?
  return existing if loaded.empty?

  loaded.map do |f|
    i = existing.index(f)
    if i
      existing.delete_at(i).tap do |t|
        keys = ["id"] + t.changes.keys + (f.attribute_names - t.attribute_names)
        # FIXME: this call to attributes causes many NoMethodErrors
        attributes = f.attributes
        (attributes.keys - keys).each do |k|
          t.send("#{k}=", attributes[k])
        end
      end
    else
      f
    end
  end + existing
end

#null_scope?Boolean

Returns:

  • (Boolean)


324
325
326
# File 'lib/active_fedora/associations/collection_association.rb', line 324

def null_scope?
  owner.new_record? && !foreign_key_present?
end

#reader(opts = false) ⇒ Object

Implements the reader method, e.g. foo.items for Foo.has_many :items

Parameters:

  • opts (Boolean, Hash) (defaults to: false)

    if true, force a reload

Options Hash (opts):

  • :response_format (Symbol)

    can be ':solr' to return a solr result.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/active_fedora/associations/collection_association.rb', line 14

def reader(opts = false)
  if opts.kind_of?(Hash)
    if opts.delete(:response_format) == :solr
      return load_from_solr(opts)
    end
    raise ArgumentError, "Hash parameter must include :response_format=>:solr (#{opts.inspect})"
  else
    force_reload = opts
  end
  reload if force_reload || stale_target?
  @proxy ||= CollectionProxy.new(self)
end

#replace(other_array) ⇒ Object

Replace this collection with other_array This will perform a diff and delete/add only records that have changed.



107
108
109
110
111
112
113
114
115
116
# File 'lib/active_fedora/associations/collection_association.rb', line 107

def replace(other_array)
  other_array.each { |val| raise_on_type_mismatch(val) }

  load_target
  other   = other_array.size < 100 ? other_array : other_array.to_set
  current = @target.size < 100 ? @target : @target.to_set

  delete(@target.select { |v| !other.include?(v) })
  concat(other_array.select { |v| !current.include?(v) })
end

#resetObject



54
55
56
57
# File 'lib/active_fedora/associations/collection_association.rb', line 54

def reset
  reset_target!
  @loaded = false
end

#scope(opts = {}) ⇒ Object



318
319
320
321
322
# File 'lib/active_fedora/associations/collection_association.rb', line 318

def scope(opts = {})
  scope = super()
  scope.none! if opts.fetch(:nullify, true) && null_scope?
  scope
end

#sizeObject

Returns the size of the collection

If the collection has been already loaded size and length are equivalent. If not and you are going to need the records anyway length will take one less query. Otherwise size is more efficient.

This method is abstract in the sense that it relies on count_records, which is a method descendants have to provide.



79
80
81
82
83
84
85
86
87
88
# File 'lib/active_fedora/associations/collection_association.rb', line 79

def size
  if @owner.new_record? && @target
    @target.size
  elsif !loaded? && @target.is_a?(Array)
    unsaved_records = @target.select { |r| r.new_record? }
    unsaved_records.size + count_records
  else
    count_records
  end
end

#target=(target) ⇒ Object

Sets the target of this proxy to \target, and the loaded flag to true.



240
241
242
243
# File 'lib/active_fedora/associations/collection_association.rb', line 240

def target=(target)
  @target = [target]
  loaded!
end

#to_aryObject Also known as: to_a



138
139
140
# File 'lib/active_fedora/associations/collection_association.rb', line 138

def to_ary
  load_target.dup
end

#writer(records) ⇒ Object

Implements the writer method, e.g. foo.items= for Foo.has_many :items



28
29
30
# File 'lib/active_fedora/associations/collection_association.rb', line 28

def writer(records)
  replace(records)
end