Class: ActiveSimilar::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/active_similar/query.rb

Overview

Queries similar models through most common associations.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, through:, prefix: 'similar') ⇒ Query

Returns a new instance of Query.

Parameters:

  • scope (ActiveRecord::Relation)
  • through (Symbol Array<Symbol>)
  • prefix (String) (defaults to: 'similar')

Raises:

  • (TypeError)

    if scope has invalid type



22
23
24
25
26
27
28
29
# File 'lib/active_similar/query.rb', line 22

def initialize(scope, through:, prefix: 'similar')
  relation = ActiveRecord::Relation
  scope.is_a?(relation) || raise(TypeError, "scope must be #{relation}")

  @scope   = scope
  @through = Array(through)
  @prefix  = prefix
end

Instance Attribute Details

#prefixObject (readonly)

Returns the value of attribute prefix.



8
9
10
# File 'lib/active_similar/query.rb', line 8

def prefix
  @prefix
end

#scopeObject (readonly)

Returns the value of attribute scope.



8
9
10
# File 'lib/active_similar/query.rb', line 8

def scope
  @scope
end

#throughObject (readonly)

Returns the value of attribute through.



8
9
10
# File 'lib/active_similar/query.rb', line 8

def through
  @through
end

Instance Method Details

#inspectObject

:nodoc:



44
45
46
# File 'lib/active_similar/query.rb', line 44

def inspect # :nodoc:
  "#<#{self.class.name} model=#{klass.name} through=#{through} prefix=#{prefix}>"
end

#with(other) ⇒ ActiveRecord::Relation

Returns records similar to other record.

Parameters:

  • other (Integer ActiveRecord::Base)

Returns:

  • (ActiveRecord::Relation)


35
36
37
38
39
40
41
42
# File 'lib/active_similar/query.rb', line 35

def with(other)
  scope
    .merge(subquery(other))
    .where.not(primary_key => other)
    .select(*select_columns)
    .group(*group_columns)
    .order(count_column => :desc)
end