Module: Pluckers::Features::Base::HasAndBelongsToManyReflections

Included in:
HasAndBelongsToManyReflections
Defined in:
lib/pluckers/features/base/has_and_belongs_to_many_reflections.rb

Overview

This module implements plucking has_and_belongs_to_many relationships in a recursive way.

The options used in this feature are:

* reflections: A hash of the reflections we will pluck recursively. The
  key of this hash will be the name of the reflection and the value is
  another hash of options.

  - scope: You can limit the scope of the objects plucked. E.g, you
    could use Author.active instead of Author.all. Notice that .all is
    the default.

  - plucker: You can use a custom plucker instead of Pluckers::Base in
    case you want any specific logic. Pluckers::Base is the default one.

  - Any other option will be passed to the plucker, so you can send any
    other regular option such as attributes, custom ones or even more
    reflections. Recursivity FTW!!

Instance Method Summary collapse

Instance Method Details

#build_resultsObject

In this method we get the reflections and for each one creates and executes a new plucker.

This pluck gives the whole process a recursive character and options for that plucker may be passed in the options hash.



68
69
70
71
72
73
74
75
76
# File 'lib/pluckers/features/base/has_and_belongs_to_many_reflections.rb', line 68

def build_results
  super

  return if @has_and_belongs_to_many_reflections.blank?

  build_only_ids_has_and_belongs_to_many_reflections
  build_complete_has_and_belongs_to_many_reflections

end

#configure_queryObject

Here we obtain the has_many reflections to include in the pluck operation and also include the relation foreign key in the attributes to pluck for this model.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/pluckers/features/base/has_and_belongs_to_many_reflections.rb', line 41

def configure_query
  super

  pluck_reflections = @options[:reflections] || {}

  return if pluck_reflections.blank?

  @has_and_belongs_to_many_reflections = { }

  # We iterate through the class reflections passed as options
  @klass_reflections.slice(*pluck_reflections.keys).
  # And select those that are HasMany
    select{|_, r| active_record_has_and_belongs_to_many_reflection?(r) }.
  # And store them in the has_many_reflection hash that will be used later
    each do |name, reflection|
      name = name.to_sym
      @has_and_belongs_to_many_reflections[name] = pluck_reflections[name]
    end

end