Sha256: 690950a40698eb4948a0d2ca527a02171d494c74a519828a3744ad45c363d937

Contents?: true

Size: 1.85 KB

Versions: 8

Compression:

Stored size: 1.85 KB

Contents

module Protoable
  module Scope
    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

    # 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
    #
    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

    # 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)
    #
    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

    # :noapi:
    def searchable_fields
      @_searchable_fields ||= {}
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
protobuf-activerecord-1.2.4 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.2.3 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.2.2 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.2.1 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.2.0 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.2.0.rc1 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.1.1 lib/protobuf/activerecord/protoable/scope.rb
protobuf-activerecord-1.1.0 lib/protoable/scope.rb