Class: Ush::Sqlite

Inherits:
Object
  • Object
show all
Defined in:
lib/ush/db/sqlite.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = File.expand_path(File.join(File.dirname(__FILE__), '../../../db/ush.sqlite.db'))) ⇒ Sqlite

Initializes the database connection and creates the table if it doesn’t exist already



10
11
12
13
14
15
# File 'lib/ush/db/sqlite.rb', line 10

def initialize(file = File.expand_path(File.join(File.dirname(__FILE__), '../../../db/ush.sqlite.db')))
  FileUtils.touch(file) unless File.exist?(file) # create the db if it doesnt already exist
  puts "Database is being stored at #{file}"
  @db = SQLite3::Database.new(file)
  @db.execute 'CREATE TABLE IF NOT EXISTS pairings(url TEXT, code TEXT)'
end

Instance Attribute Details

#dbObject

An accessor to the underlying Sqlite3::Database instance



7
8
9
# File 'lib/ush/db/sqlite.rb', line 7

def db
  @db
end

Instance Method Details

#add_url(url, shortcode) ⇒ Object

Adds a url and shortcode association to the database



18
19
20
21
22
23
24
25
# File 'lib/ush/db/sqlite.rb', line 18

def add_url(url, shortcode)
  @db.execute "INSERT INTO pairings VALUES('#{url}', '#{shortcode}')"
  return true
rescue SQLite3::Exception => e
  puts 'Unable to add url:'
  puts e
  return false
end

#code_exists?(code) ⇒ Boolean

Checks if the given shortcode exists within the database

Returns:

  • (Boolean)


40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ush/db/sqlite.rb', line 40

def code_exists?(code)
  statement = @db.prepare("SELECT * FROM pairings WHERE code='#{code}'")
  rs = statement.execute
  rs.each do |row|
    return true if row != ''
    return false
  end
rescue SQLite3::Exception => e
  puts "Unable to get url for code #{code}"
  puts e
end

#get_url_for_code(code) ⇒ Object

Gets the associated url for the given shortcode



28
29
30
31
32
33
34
35
36
37
# File 'lib/ush/db/sqlite.rb', line 28

def get_url_for_code(code)
  statement = @db.prepare("SELECT * FROM pairings WHERE code='#{code}'")
  rs = statement.execute
  rs.each do |row|
    return row[0] # if row.class == Array # This is the first url, shouldn't be more than one.
  end
rescue SQLite3::Exception => e
  puts "Unable to get url for code #{code}"
  puts e
end