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



116
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
# File 'lib/moped/protocol/message.rb', line 116

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

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

  fields << name
end