Module: CouchbaseOrm::N1ql::ClassMethods

Defined in:
lib/couchbase-orm/n1ql.rb

Constant Summary collapse

N1QL_DEFAULTS =
{ include_docs: true }

Instance Method Summary collapse

Instance Method Details

#index_n1ql(attr, validate: true, find_method: nil, n1ql_method: nil) ⇒ Object

add a n1ql query and lookup method to the model for finding all records using a value in the supplied attr.



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/couchbase-orm/n1ql.rb', line 77

def index_n1ql(attr, validate: true, find_method: nil, n1ql_method: nil)
    n1ql_method ||= "by_#{attr}"
    find_method ||= "find_#{n1ql_method}"

    validates(attr, presence: true) if validate
    n1ql n1ql_method, emit_key: attr

    define_singleton_method find_method do |value|
        send n1ql_method, key: [value]
    end
end

#n1ql(name, query_fn: nil, emit_key: [], custom_order: nil, **options) ⇒ Object

Defines a query N1QL for the model

TODO: add range keys [:startkey, :endkey]

Examples:

Define some N1QL queries for a model

class Post < CouchbaseOrm::Base
  n1ql :by_rating, emit_key: :rating
end

Post.by_rating do |response|
  # ...
end

Parameters:

  • names (Symbol, String, Array)

    names of the views

  • options (Hash)

    options passed to the Couchbase::N1QL

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/couchbase-orm/n1ql.rb', line 45

def n1ql(name, query_fn: nil, emit_key: [], custom_order: nil, **options)
    raise ArgumentError, "#{self} already respond_to? #{name}" if self.respond_to?(name)

    emit_key = Array.wrap(emit_key)
    emit_key.each do |key|
        raise "unknown emit_key attribute for n1ql :#{name}, emit_key: :#{key}" if key && !attribute_names.include?(key.to_s)
    end
    options = N1QL_DEFAULTS.merge(options)
    method_opts = {}
    method_opts[:emit_key] = emit_key

    @indexes ||= {}
    @indexes[name] = method_opts

    singleton_class.__send__(:define_method, name) do |key: NO_VALUE, **opts, &result_modifier|
        opts = options.merge(opts).reverse_merge(scan_consistency: CouchbaseOrm::N1ql.config[:scan_consistency])
        values = key == NO_VALUE ? NO_VALUE : convert_values(method_opts[:emit_key], key)
        current_query = run_query(method_opts[:emit_key], values, query_fn, custom_order: custom_order, **opts.except(:include_docs, :key))
        if result_modifier
            opts[:include_docs] = true
            current_query.results &result_modifier
        elsif opts[:include_docs]
            current_query.results { |res| find(res) }
        else
            current_query.results
        end
    end
end