module Rid # Holds Application config # class App attr_reader :db_url, :db attr_accessor :root # Initialize app with an options object, # which behaves like an open struct. # # Options are: # root: specify app root directory # database: set database name # def initialize(options = OpenStruct.new) @root = options.root @root ||= find_root @root = Pathname.new(@root) @db_url = options.database @db_url ||= read_db_url end # Returns an instance of Rid::Database, # configured with db_name. # def db return unless @db_url @db ||= Rid::Database.new(@db_url) end # List application documents. # Each entry is a filename. # def documents @documents ||= Dir[root.join("*")]. select { |f| File.directory?(f) && File.file?(File.join(f, '_id')) }. map { |f| Rid::Document.new :path => f } end private def read_db_url filename = root.join('_database') File.read(filename).strip rescue Errno::ENOENT end # from Rails: # Returns application root. # traverses the directory to top, # until it finds app config file. def find_root cwd = Dir.pwd return cwd if File.exists?(File.join(cwd, '_database')) Dir.chdir('..') do find_root unless cwd == Dir.pwd end rescue SystemCallError # could not chdir, no problem just return end end end