Module: DbMod::Create

Defined in:
lib/db_mod/create.rb

Overview

Provides the create function which is added to all modules which include DbMod. This function creates an object which exposes the functions defined in the module, allowing them to be used without namespace pollution.

The function may be used in two forms. It may be called with an options hash, in which case #db_connect will be used to create a new connection object. Alternatively an existing connection object may be passed, which will be used for all database queries.

Class Method Summary collapse

Class Method Details

.instantiable_class(mod) ⇒ Object (private)

Creates a class which inherits from the given module and can be instantiated with either a connection object or some connection options.

Parameters:

  • mod (Module)


37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/db_mod/create.rb', line 37

def self.instantiable_class(mod)
  Class.new do
    include mod

    define_method(:initialize) do |options|
      if options.is_a? PGconn
        self.conn = options
      else
        db_connect options
      end
    end
  end
end

.setup(mod) ⇒ Object

Defines a module-specific create function for a module that has just had DbMod included.

Parameters:

  • mod (Module)


20
21
22
23
24
25
26
27
28
# File 'lib/db_mod/create.rb', line 20

def self.setup(mod)
  mod.class.instance_eval do
    define_method(:create) do |options = {}|
      @instantiable_class ||= Create.instantiable_class(self)

      @instantiable_class.new(options)
    end
  end
end