lib/groovy.rb in groovy-0.1.0 vs lib/groovy.rb in groovy-0.1.1
- old
+ new
@@ -1,19 +1,60 @@
require 'groonga'
require File.expand_path(File.dirname(__FILE__)) + '/groovy/model'
module Groovy
- VERSION = '0.1.0'.freeze
+ VERSION = '0.1.1'.freeze
- def self.init(db_path, opts = {})
- if File.exist?(db_path)
- puts "Opening DB"
- Groonga::Database.open(db_path)
- else
- dir = File.dirname(db_path)
- puts "Creating DB in #{dir}"
- FileUtils.mkdir_p(dir)
- Groonga::Database.create(path: db_path)
+ class << self
+
+ def contexts
+ @contexts ||= {}
end
+
+ def [](key)
+ contexts[key.to_sym]
+ end
+
+ def first_context_name
+ contexts.keys.first
+ end
+
+ def open(db_path, name = :default, opts = {})
+ raise "Context already defined: #{name}" if contexts[name.to_sym]
+ contexts[name.to_sym] = if name == :default
+ Groonga::Context.default.tap { |ctx| open_or_create_db(ctx, db_path) }
+ else
+ init_context(db_path, opts)
+ end
+ end
+
+ def logger=(obj)
+ @logger = obj
+ end
+
+ def logger
+ @logger ||= Logger.new(STDOUT)
+ end
+
+ private
+
+ def init_context(db_path, opts)
+ Groonga::Context.new(opts).tap do |ctx|
+ open_or_create_db(ctx, db_path)
+ end
+ end
+
+ def open_or_create_db(ctx, path)
+ if File.exist?(path)
+ logger.info "Opening DB at #{path}"
+ ctx.open_database(path)
+ else
+ dir = File.dirname(path)
+ logger.info "Creating DB in #{dir}"
+ FileUtils.mkdir_p(dir)
+ ctx.create_database(path)
+ end
+ end
+
end
-end
\ No newline at end of file
+end