Method: NoBrainer::Document::Index::ClassMethods#index

Defined in:
lib/no_brainer/document/index.rb

#index(name, *args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/no_brainer/document/index.rb', line 14

def index(name, *args)
  name = case name
    when String then name.to_sym
    when Symbol then name
    when Array  then args.unshift(name); name.map(&:to_s).join('_').to_sym
    else raise ArgumentError, "Incorrect index specification"
  end

  options = args.extract_options!
  options.assert_valid_keys(*VALID_INDEX_OPTIONS)

  raise "Too many arguments: #{args}" if args.size > 1

  kind, what = case args.first
    when nil    then [:single,   name.to_sym]
    when Array  then [:compound, args.first.map(&:to_sym)]
    when Proc   then [:proc,     args.first]
    else raise "Index argument must be a lambda or a list of fields"
  end

  if name.in?(NoBrainer::Document::Attributes::RESERVED_FIELD_NAMES)
    raise "The index name `:#{name}' is reserved. Please use another one."
  end

  if has_field?(name) && kind != :single
    raise "The field `#{name}' is already declared. Please remove its definition first."
  end

  if kind == :compound && what.size < 2
    raise "Compound indexes only make sense with 2 or more fields"
  end

  store_as = options.delete(:store_as)
  store_as ||= fields[name][:store_as] if has_field?(name)
  store_as ||= name
  store_as = store_as.to_sym

  indexes[name] = NoBrainer::Document::Index::Index.new(self.root_class, name, store_as,
    kind, what, options[:external], options[:geo], options[:multi], nil)
end