Class: ActiveRecordHas::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_has/scope.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, association, relation, **options, &block) ⇒ Scope

Returns a new instance of Scope.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/active_record_has/scope.rb', line 7

def initialize(model, association, relation, **options, &block)
  @model = model
  @association = association
  @block = block
  @options = options
  @reflection ||=
    if association.is_a? Symbol
      @relation = relation if relation.is_a? ActiveRecord::Relation
      @reflection = reflections[association.to_s]
    elsif association.is_a? ActiveRecord::Relation
      @relation = association
      model_name = association.model_name
      @reflection = reflections[model_name.plural] || reflections[model_name.singular]
    else
      nil
    end
end

Instance Attribute Details

#associationObject (readonly)

Returns the value of attribute association.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def association
  @association
end

#blockObject (readonly)

Returns the value of attribute block.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def block
  @block
end

#modelObject (readonly)

Returns the value of attribute model.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def model
  @model
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def options
  @options
end

#reflectionObject (readonly)

Returns the value of attribute reflection.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def reflection
  @reflection
end

#relationObject (readonly)

Returns the value of attribute relation.



5
6
7
# File 'lib/active_record_has/scope.rb', line 5

def relation
  @relation
end

Instance Method Details

#existsObject



52
53
54
# File 'lib/active_record_has/scope.rb', line 52

def exists
  scope.arel.exists
end

#scopeObject

Raises:



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/active_record_has/scope.rb', line 39

def scope
  raise Error unless reflection

  @scope ||= 
    begin
      result = reflection.foreign_scope
      result = result.instance_eval(&block) if block
      result = result.merge(relation) if relation
      result = result.where(**options) if options.present?
      result
    end
end