module Mongoid::Followit::Queryable

Internal: Module that add query capabilities Follower/Followee model.

Examples

module Follower
  def self.included(base)
    base.class_eval do
      include Mongoid::Followit::Queryable
    end
  end
end

module Followee
  def self.included(base)
    base.class_eval do
      include Mongoid::Followit::Queryable
    end
  end
end

Constants

FOLLOW_OPTIONS

Internal: Hash of options to build a query for the Follow collection.

Public Instance Methods

follow_collection_for_a(behavior, criteria:) click to toggle source
# File lib/mongoid_followit/queryable.rb, line 44
def follow_collection_for_a(behavior, criteria:)
  options = query_options_for_a(behavior)
  group_class = FOLLOW_OPTIONS[behavior][:class]
  grouped = Follow.where(options).group_by { |f| f.send(group_class) }
  if criteria
    collection_as_criteria(grouped, behavior)
  else
    collection_as_array(grouped, behavior)
  end
end

Private Instance Methods

collection_as_array(grouped, behavior) click to toggle source
# File lib/mongoid_followit/queryable.rb, line 74
def collection_as_array(grouped, behavior)
  behavior_class = FOLLOW_OPTIONS[behavior][:class]
  behavior_id = FOLLOW_OPTIONS[behavior][:id]
  grouped.values.flatten.map do |follow|
    follow.send(behavior_class).constantize.find(follow.send(behavior_id))
  end
end
collection_as_criteria(grouped, behavior) click to toggle source
# File lib/mongoid_followit/queryable.rb, line 66
def collection_as_criteria(grouped, behavior)
  return Follow.none if grouped.empty?
  raise FOLLOW_OPTIONS[behavior][:exception] if grouped.length > 1
  klazz = grouped.keys.first
  ids = grouped[klazz].map { |f| f.send(FOLLOW_OPTIONS[behavior][:id]) }
  klazz.constantize.in(id: ids)
end
query_options_for_a(behavior) click to toggle source
# File lib/mongoid_followit/queryable.rb, line 57
def query_options_for_a(behavior)
  options_class = FOLLOW_OPTIONS[behavior][:opposite_class]
  options_id = FOLLOW_OPTIONS[behavior][:opposite_id]
  {
    options_class => self.class,
    options_id => id
  }
end