Class: Vines::Services::Storage::CouchDB

Inherits:
Vines::Services::Storage show all
Defined in:
lib/vines/services/storage/couchdb.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Methods inherited from Vines::Services::Storage

from_name, register

Constructor Details

#initialize(&block) ⇒ CouchDB

Returns a new instance of CouchDB.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/vines/services/storage/couchdb.rb', line 39

def initialize(&block)
  @config = {}
  instance_eval(&block)
  [:host, :port, :database, :index_dir].each do |key|
    raise "Must provide #{key}" unless @config[key]
  end

  @config[:index_dir] = File.expand_path(@config[:index_dir])
  unless File.directory?(@config[:index_dir]) && File.writable?(@config[:index_dir])
    raise 'Must provide a writable index directory'
  end

  @url = url(@config)
  init_couch_rest

  db = "%s-%s-%s.db" % [host, port, database]
  @index = Indexer[File.join(@config[:index_dir], db)]
end

Instance Method Details

#create_viewsObject



102
103
104
105
106
107
108
109
110
111
# File 'lib/vines/services/storage/couchdb.rb', line 102

def create_views
  EM.run do
    Fiber.new do
      CouchRest::Model::Base.subclasses.each do |klass|
        klass.save_design_doc! if klass.respond_to?(:save_design_doc!)
      end
      EM.stop
    end.resume
  end
end

#delete(path, &callback) ⇒ Object



66
67
68
69
70
71
72
73
74
# File 'lib/vines/services/storage/couchdb.rb', line 66

def delete(path, &callback)
  http(path, :get) do |doc|
    if doc
      http("#{path}?rev=#{doc['_rev']}", :delete, &callback)
    else
      yield
    end
  end
end

#get(path, &callback) ⇒ Object



58
59
60
# File 'lib/vines/services/storage/couchdb.rb', line 58

def get(path, &callback)
  http(path, :get, &callback)
end

#index(system) ⇒ Object



80
81
82
# File 'lib/vines/services/storage/couchdb.rb', line 80

def index(system)
  @index << system.ohai
end

#post(path, body, &callback) ⇒ Object



62
63
64
# File 'lib/vines/services/storage/couchdb.rb', line 62

def post(path, body, &callback)
  http(path, :post, body, &callback)
end

#query(sql, *params, &callback) ⇒ Object



84
85
86
# File 'lib/vines/services/storage/couchdb.rb', line 84

def query(sql, *params, &callback)
  @index.find(sql, params, &callback)
end

#save(doc, &callback) ⇒ Object



76
77
78
# File 'lib/vines/services/storage/couchdb.rb', line 76

def save(doc, &callback)
  http('', :post, doc.to_json, &callback)
end

#store_file(path) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/vines/services/storage/couchdb.rb', line 88

def store_file(path)
  file = CouchModels::Upload.find_by_name(File.basename(path))
  unless file
    File.delete(path)
    return
  end

  http = EM::HttpRequest.new("#{@url}/#{file.id}/data?rev=#{file.rev}").put(
    head: {'Content-Type' => 'application/octet-stream'},
    file: path
  )
  http.callback {|chunk| yield }
end