Method: Moped::Protocol::Message::ClassMethods#document

Defined in:
lib/moped/protocol/message.rb

#document(name, options = {}) ⇒ Object

Declare a BSON Document field.

Examples:

class Update < Message
  document :selector
end

optional document field

class Query < Message
  document :selector
  document :fields, optional: true
end

array of documents

class Reply < Message
  document :documents, type: :array
end

Parameters:

  • name (String)

    the name of this field

  • options (Hash) (defaults to: {})

    the options for this field

Options Hash (options):

  • :type (:array)

    specify an array of documents

  • :optional (Boolean)

    specify this field as optional



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/moped/protocol/message.rb', line 151

def document(name, options = {})
  attr_accessor name

  if options[:optional]
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def serialize_#{name}(buffer)
        buffer << #{name}.to_bson if #{name}
      end
    RUBY
  elsif options[:type] == :array
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def serialize_#{name}(buffer)
        #{name}.each do |document|
          buffer << document.to_bson
        end
      end
    RUBY
  else
    class_eval <<-RUBY, __FILE__, __LINE__ + 1
      def serialize_#{name}(buffer)
        buffer << #{name}.to_bson
      end
    RUBY
  end

  fields << name
end