Module: ScanDB::Database

Defined in:
lib/scandb/database.rb

Constant Summary collapse

CONFIG_FILE =

Database configuration file

File.join(Config::PATH,'database.yml')
DEFAULT_LOG_PATH =

Default log path

File.join(Config::PATH,'scandb.log')
DEFAULT_LOG_LEVEL =

Default log level

:info
DEFAULT_CONFIG =

Default database configuration

"sqlite3://" + File.join(Config::PATH,'scandb.db')

Class Method Summary collapse

Class Method Details

.configObject

Returns the Database configuration that is stored in the CONFIG_FILE. Defaults to DEFAULT_CONFIG if CONFIG_FILE does not exist.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/scandb/database.rb', line 56

def Database.config
  unless class_variable_defined?('@@scandb_database_config')
    @@scandb_database_config = DEFAULT_CONFIG

    if File.file?(CONFIG_FILE)
      conf = YAML.load(CONFIG_FILE)

      unless (conf.kind_of?(Hash) || conf.kind_of?(String))
        raise(InvalidDatabaseConfig,"#{CONFIG_FILE} must contain either a Hash or a String",caller)
      end

      @@scandb_database_config = conf
    end
  end

  return @@scandb_database_config ||= DEFAULT_CONFIG
end

.config=(configuration) ⇒ Object

Sets the Database configuration to the specified configuration.



77
78
79
# File 'lib/scandb/database.rb', line 77

def Database.config=(configuration)
  @@scandb_database_config = configuration
end

.setup(configuration = Database.config, &block) ⇒ Object

Sets up the Database with the given configuration. If _configuration is not given, DEFAULT_CONFIG will be used to setup the Database.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/scandb/database.rb', line 104

def Database.setup(configuration=Database.config,&block)
  Database.setup_log
  DataMapper.setup(Model::REPOSITORY_NAME, configuration)

  block.call if block

  # sourced from http://gist.github.com/3010
  # in order to fix a has-many lazy-loading bug
  # in dm-core <= 0.9.4
  descendants = DataMapper::Resource.descendants.dup
  descendants.each do |model|
    descendants.merge(model.descendants) if model.respond_to?(:descendants)
  end
  descendants.each do |model|
    model.relationships.each_value { |r| r.child_key if r.child_model == model }
  end

  DataMapper.auto_upgrade!(Model::REPOSITORY_NAME)
  return nil
end

.setup_log(options = {}) ⇒ Object

Setup the Database log with the given options.

options may contain the following keys:

:path

The path of the log file. Defaults to DEFAULT_LOG_PATH.

:stream

The stream to use for the log.

:level

The level of messages to log.



90
91
92
93
94
95
96
97
# File 'lib/scandb/database.rb', line 90

def Database.setup_log(options={})
  path = (options[:path] || DEFAULT_LOG_PATH)
  stream = (options[:stream] || File.new(path,'w+'))
  level = (options[:level] || DEFAULT_LOG_LEVEL)

  DataMapper::Logger.new(stream,level)
  return nil
end