Class: StoresInMongo::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/stores_in_mongo/builder.rb

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Builder

Returns a new instance of Builder.



4
5
6
7
# File 'lib/stores_in_mongo/builder.rb', line 4

def initialize(model)
  @model = model
  @class_given = @model.stores_in_mongo_options[:class_name].present?
end

Instance Method Details

#add_field(field_name, data_type) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/stores_in_mongo/builder.rb', line 38

def add_field(field_name, data_type)
  @model.stores_in_mongo_options[:class_name].constantize.field field_name, :type => data_type, default: data_type.try(:new) if !@class_given

  @model::MongoDocumentMethods.instance_exec(field_name) do |field_name|
    # getter
    define_method(field_name) do
      mongo_document.public_send(field_name)
    end

    # setter
    define_method("#{field_name}=") do |data|
      mongo_document.public_send("#{field_name}=", data)
    end

  end
end

#build(&blk) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/stores_in_mongo/builder.rb', line 9

def build(&blk)
  if !@class_given
    klass = build_mongo_class
    @model.stores_in_mongo_options[:class_name] = klass.name
  end
  @model.stores_in_mongo_options[:foreign_key] ||= @model.stores_in_mongo_options[:class_name].foreign_key
  @model.include(get_document_methods_module)
  Interpreter.new(self).instance_exec(&blk)
end

#build_mongo_classObject



19
20
21
22
23
24
# File 'lib/stores_in_mongo/builder.rb', line 19

def build_mongo_class
  klass = @model.const_set("MongoDocument", Class.new)
  klass.include Mongoid::Document
  klass.include Mongoid::Timestamps
  return klass
end

#define_session(&blk) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/stores_in_mongo/builder.rb', line 55

def define_session(&blk)
  @model.stores_in_mongo_options[:use_sessions] = true
  @model::MongoDocumentMethods.instance_exec(blk) do |blk|
    define_method("mongo_session") do
      instance_exec(&blk)
    end
  end
end

#get_document_methods_moduleObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/stores_in_mongo/builder.rb', line 26

def get_document_methods_module
  @model.const_set("MongoDocumentMethods", Module.new)
  @model::MongoDocumentMethods.include(StoresInMongo::DocumentMethods)
  @model::MongoDocumentMethods.extend ActiveSupport::Concern
  @model::MongoDocumentMethods.included do
    before_save :save_mongo_document
    after_save :clear_mongo_owner_dirty
    before_destroy :destroy_mongo_document
  end
  return @model::MongoDocumentMethods
end