Module: Protoable::Scope

Defined in:
lib/protobuf/activerecord/protoable/scope.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



3
4
5
6
7
8
9
10
11
# File 'lib/protobuf/activerecord/protoable/scope.rb', line 3

def self.extended(klass)
  klass.class_eval do
    class << self
      alias_method :by_fields, :search_scope
      alias_method :from_proto, :search_scope
      alias_method :scope_from_proto, :search_scope
    end
  end
end

Instance Method Details

#field_scope(field, scope_name) ⇒ Object

Define fields that should be searchable via ‘search_scope`. Accepts a protobuf field and an already defined scope.

Examples:

class User < ActiveRecord::Base
  scope :by_guid, lambda { |*guids| where(:guid => guids) }

  field_scope :guid, :by_guid
end


24
25
26
27
28
29
30
# File 'lib/protobuf/activerecord/protoable/scope.rb', line 24

def field_scope(field, scope_name)
  unless self.respond_to?(scope_name)
    raise Protoable::SearchScopeError, "Undefined scope :#{scope_name}. :#{scope_name} must be defined before it can be used as a field scope."
  end

  searchable_fields[field] = scope_name
end

#search_scope(proto) ⇒ Object

Builds and returns a Arel relation based on the fields that are present in the given protobuf message using the searchable fields to determine what scopes to use. Provides several aliases for variety.

Examples:

# Search starting with the default scope and searchable fields
User.search_scope(request)
User.by_fields(request)
User.from_proto(request)
User.scope_from_proto(request)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/protobuf/activerecord/protoable/scope.rb', line 44

def search_scope(proto)
  relation = scoped # Get an ARel relation to build off of

  searchable_fields.each do |field, scope_name|
    next unless proto.respond_to_and_has_and_present?(field)

    values = [ proto.__send__(field) ].flatten
    values.map!(&:to_i) if proto.get_field_by_name(field).enum?

    relation = relation.__send__(scope_name, *values)
  end

  return relation
end

#searchable_fieldsObject

:noapi:



60
61
62
# File 'lib/protobuf/activerecord/protoable/scope.rb', line 60

def searchable_fields
  @_searchable_fields ||= {}
end