Class: JsonapiCompliable::Scoping::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_compliable/scoping/base.rb

Overview

The interface for scoping logic (filter, paginate, etc).

This class defines some common behavior, such as falling back on a default if not part of the user request.

Direct Known Subclasses

DefaultFilter, ExtraFields, Filter, Paginate, Sort

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, query_hash, scope, opts = {}) ⇒ Base

Returns a new instance of Base

Parameters:

  • resource (Resource)

    the Resource instance

  • query_hash (Hash)

    the Query#to_hash node relevant to the current resource

  • scope

    the base scope object to chain/modify

  • opts (Hash) (defaults to: {})

    configuration options used by subclasses



26
27
28
29
30
31
# File 'lib/jsonapi_compliable/scoping/base.rb', line 26

def initialize(resource, query_hash, scope, opts = {})
  @query_hash = query_hash
  @resource   = resource
  @scope      = scope
  @opts       = opts
end

Instance Attribute Details

#query_hashHash (readonly)

the Query#to_hash node relevant to the current resource

Returns:

  • (Hash)

    the current value of query_hash



19
20
21
# File 'lib/jsonapi_compliable/scoping/base.rb', line 19

def query_hash
  @query_hash
end

#resourceResource (readonly)

The corresponding Resource instance

Returns:

  • (Resource)

    the current value of resource



19
20
21
# File 'lib/jsonapi_compliable/scoping/base.rb', line 19

def resource
  @resource
end

Instance Method Details

#applyObject

Apply this scoping criteria. This is where we would chain on pagination, sorting, etc.

If #apply? returns false, does nothing. Otherwise will apply the default logic:

# no block, run default logic via adapter
allow_filter :name

Or the customized proc:

allow_filter :name do |scope, value|
  scope.where("upper(name) = ?", value.upcase)
end

Returns:

  • the scope object

See Also:



50
51
52
53
54
55
56
# File 'lib/jsonapi_compliable/scoping/base.rb', line 50

def apply
  if apply?
    apply_standard_or_override
  else
    @scope
  end
end

#apply?Boolean

Should we process this scope logic?

Useful for when we want to explicitly opt-out on certain requests, or avoid a default in certain contexts.

Returns:

  • (Boolean)

    if we should apply this scope logic



64
65
66
# File 'lib/jsonapi_compliable/scoping/base.rb', line 64

def apply?
  true
end

#apply_custom_scopeObject

Defines how to call/apply the custom scoping logic provided by the user.



75
76
77
# File 'lib/jsonapi_compliable/scoping/base.rb', line 75

def apply_custom_scope
  raise 'override in subclass'
end

#apply_standard_scopeObject

Defines how to call/apply the default scoping logic



69
70
71
# File 'lib/jsonapi_compliable/scoping/base.rb', line 69

def apply_standard_scope
  raise 'override in subclass'
end