require 'groonga' require File.expand_path(File.dirname(__FILE__)) + '/groovy/model' module Groovy 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