Class: Ush::Sqlite
- Inherits:
-
Object
- Object
- Ush::Sqlite
- Defined in:
- lib/ush/db/sqlite.rb
Instance Attribute Summary collapse
-
#db ⇒ Object
An accessor to the underlying Sqlite3::Database instance.
Instance Method Summary collapse
-
#add_url(url, shortcode) ⇒ Object
Adds a url and shortcode association to the database.
-
#code_exists?(code) ⇒ Boolean
Checks if the given shortcode exists within the database.
-
#get_url_for_code(code) ⇒ Object
Gets the associated url for the given shortcode.
-
#initialize(file = File.expand_path(File.join(File.dirname(__FILE__), '../../../db/ush.sqlite.db'))) ⇒ Sqlite
constructor
Initializes the database connection and creates the table if it doesn’t exist already.
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.(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
#db ⇒ Object
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
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 |