Class: CustomDbDriver::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/custom_db_driver/base.rb

Direct Known Subclasses

MongoDb, MySql

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.modelObject

Returns the value of attribute model.



4
5
6
# File 'lib/custom_db_driver/base.rb', line 4

def model
  @model
end

Class Method Details

.belongs_to(attr_name, options = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/custom_db_driver/base.rb', line 42

def belongs_to(attr_name, options={})
  options[:class_name] ||= attr_name.to_s.camelize
  options[:foreign_key] ||= "#{options[:class_name].underscore}_id"
  @model.class_eval do
    define_method(attr_name) do
     result = options[:class_name].constantize.where("id" => self.send(options[:foreign_key]))
     result.first
    end
  end
end

.create_asscociation(model, block) ⇒ Object



6
7
8
9
# File 'lib/custom_db_driver/base.rb', line 6

def create_asscociation(model, block)
  @model = model
  class_eval(&block)
end

.has_many(attr_name, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/custom_db_driver/base.rb', line 11

def has_many(attr_name, options = {})
  options[:class_name] ||= attr_name.to_s.singularize.camelize
  options[:foreign_key] ||= "#{attr_name.to_s.singularize}_id"
  @model.class_eval do
    define_method(attr_name) do
     options[:class_name].constantize.where(options[:foreign_key] => self.id)
    end
  end
end

.has_one(attr_name, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/custom_db_driver/base.rb', line 21

def has_one(attr_name, options = {})
  options[:class_name] ||= attr_name.to_s.camelize
  options[:foreign_key] ||= "#{self.class.to_s.underscore}_id"
  options[:primary_key] ||= "id"
  @model.class_eval do
    define_method(attr_name) do
     options[:class_name].constantize.where(options[:foreign_key] => self.send(options[:primary_key])).try(:first)
    end

    define_method "create_#{attr_name}" do |attr_options = {}|
      attr_options.merge!(options[:foreign_key] => self.send(options[:primary_key]))
      options[:class_name].constantize.create(attr_options)
    end

    define_method "build_#{attr_name}" do |attr_options = {}|
      attr_options.merge!(options[:foreign_key] => self.send(options[:primary_key]))
      options[:class_name].constantize.new(attr_options)
    end
  end
end