Sha256: 66e0423ff072af5a3cdfdbde225f5d00b317e286ea3115375ecea33f5d67ec80

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

require 'groonga'
require File.expand_path(File.dirname(__FILE__)) + '/groovy/model'

module Groovy

  class Error < StandardError; end
  class ContextNotFound < Error; end
  class ContextAlreadyClosed < Error; end

  class << self

    def contexts
      @contexts ||= {}
    end

    def [](name)
      contexts[name.to_sym]
    end

    def first_context_name
      contexts.keys.first
    end

    def open(db_path, name = :default, opts = {})
      unless db_path.is_a?(String)
        raise ArgumentError, "Invalid db_path: #{db_path}"
      end

      if contexts[name.to_sym]
        raise ArgumentError, "Context already defined: #{name}"
      end

      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 close(name = :default)
      ctx = contexts[name.to_sym] or raise ContextNotFound.new(name)
      contexts.delete(name.to_sym)
      ctx.close
    rescue Groonga::Closed => e
      raise ContextAlreadyClosed
    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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
groovy-0.4.1 lib/groovy.rb
groovy-0.4.0 lib/groovy.rb