Class: JsonApiModel::Scope

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class) ⇒ Scope

Returns a new instance of Scope.



3
4
5
6
7
# File 'lib/json_api_model/scope.rb', line 3

def initialize( model_class )
  @model_class  = model_class
  @client_scope = JsonApiClient::Query::Builder.new( model_class.client_class )
  @cache        = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/json_api_model/scope.rb', line 45

def method_missing( m, *args, &block )
  if @client_scope.respond_to? m
    _new_scope @client_scope.send( m, *args, &block )
  else
    all.send m, *args, &block
  end
end

Instance Attribute Details

#client_scopeObject

Returns the value of attribute client_scope.



53
54
55
# File 'lib/json_api_model/scope.rb', line 53

def client_scope
  @client_scope
end

Instance Method Details

#find(args = {}) ⇒ Object Also known as: to_a, all



9
10
11
12
13
14
15
16
17
18
# File 'lib/json_api_model/scope.rb', line 9

def find( args = {} )
  JsonApiModel.instrumenter.instrument 'find.json_api_model',
                                        args: args,
                                        url: url do
    cache_or_find args do
      results = @client_scope.find args
      ResultSet.new( results, @model_class )
    end
  end
end

#firstObject



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/json_api_model/scope.rb', line 23

def first
  JsonApiModel.instrumenter.instrument 'first.json_api_model', url: url do
    # if the non-first query has already been executed, there's no need to make the call again
    if cached?
      cache.first
    else
      cache_or_find :first do
        @model_class.new_from_client @client_scope.first
      end
    end
  end
end

#lastObject



36
37
38
39
40
41
42
43
# File 'lib/json_api_model/scope.rb', line 36

def last
  JsonApiModel.instrumenter.instrument 'last.json_api_model', url: url do
    # this is a separate call always because the last record may exceed page size
    cache_or_find :last do
      @model_class.new_from_client @client_scope.last
    end
  end
end