Module: Mongoid::Shardable::ClassMethods

Defined in:
lib/mongoid/shardable.rb

Instance Method Summary collapse

Instance Method Details

#shard_key(*args) ⇒ Object

Specifies a shard key with the field(s) specified.

Examples:

Specify the shard key.


class Person
  include Mongoid::Document
  field :first_name, :type => String
  field :last_name, :type => String

  shard_key first_name: 1, last_name: 1
end

Raises:

  • (ArgumentError)


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/mongoid/shardable.rb', line 117

def shard_key(*args)
  unless args.first.is_a?(Hash)
    # Shorthand syntax
    raise ArgumentError, 'Shorthand shard_key syntax does not permit options' if args.last.is_a?(Hash)

    spec = Hash[args.map do |name|
      [ name, 1 ]
    end]

    return shard_key(spec)
  end

  raise ArgumentError, 'Full shard_key syntax requires 1 or 2 arguments' if args.length > 2

  spec, options = args

  spec = Hash[spec.map do |name, value|
    value = value.to_s if value.is_a?(Symbol)
    [ database_field_name(name).to_sym, value ]
  end]

  self.shard_key_fields = spec.keys
  self.shard_config = {
    key: spec.freeze,
    options: (options || {}).dup.freeze
  }.freeze
end