Class: Kilt::DB::RethinkDb

Inherits:
Object
  • Object
show all
Defined in:
lib/kilt/db/rethink_db.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ RethinkDb

Returns a new instance of RethinkDb.



7
8
9
# File 'lib/kilt/db/rethink_db.rb', line 7

def initialize(options)
  @options = options
end

Instance Method Details

#create(object) ⇒ Object



23
24
25
26
# File 'lib/kilt/db/rethink_db.rb', line 23

def create(object)
  result = execute { objects_table.insert(object.values) }
  result['errors'] == 0
end

#delete(slug) ⇒ Object



35
36
37
38
# File 'lib/kilt/db/rethink_db.rb', line 35

def delete(slug)
  result = execute { slug_query(slug).delete() }
  result['errors'] == 0
end

#delete_allObject



40
41
42
43
44
# File 'lib/kilt/db/rethink_db.rb', line 40

def delete_all
  execute do
    @r.db(Kilt.config.test.db.db).table('objects').delete()
  end
end

#execute(&block) ⇒ Object

Make a db call



47
48
49
50
# File 'lib/kilt/db/rethink_db.rb', line 47

def execute(&block)
  setup_the_database
  block.call.run(@connection)
end

#find(slug) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/kilt/db/rethink_db.rb', line 11

def find(slug)
  results = execute { slug_query(slug).limit(1) }
  return nil unless results
  results = results.to_a
  return nil if results.first.is_a? Array
  results.first
end

#find_all_by_type(type) ⇒ Object



19
20
21
# File 'lib/kilt/db/rethink_db.rb', line 19

def find_all_by_type type
  execute { type_query(type) }.to_a
end

#setup!Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/kilt/db/rethink_db.rb', line 52

def setup!
  if @options[:host] && @options[:port]
    begin
      # See if the db exists and create it otherwise
      dbs = execute { @r.db_list }.to_a
      if !dbs.to_a.include? @options[:db]
        execute { @r.db_create(@options[:db]) }
      end

      # See if the table exists and create it otherwise
      tables = execute { @r.db(@options[:db]).table_list }.to_a
      if !tables.to_a.include? "objects"
        execute { @r.db(@options[:db]).table_create("objects", :primary_key => "unique_id") }
      end
    rescue
      raise Kilt::CantSetupDatabaseError
    end
  else
    raise Kilt::NoDatabaseConfigError
  end
end

#update(object) ⇒ Object



28
29
30
31
32
33
# File 'lib/kilt/db/rethink_db.rb', line 28

def update(object)
  result = execute do
    unique_id_query(object['unique_id']).update(object.values)
  end
  result['errors'] == 0
end