Class: Corto

Inherits:
Object
  • Object
show all
Defined in:
lib/corto.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Corto

Returns a new instance of Corto.



9
10
11
12
13
14
15
16
17
18
# File 'lib/corto.rb', line 9

def initialize (options={})
  @db_name= options["db_name"]
  @db_name= './db/corto.db' unless options.has_key? "db_name"
  @use_db= options["use_db"]
  @use_db= true unless options.has_key? "use_db"

  if @use_db
    init_db
  end
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



7
8
9
# File 'lib/corto.rb', line 7

def db
  @db
end

#db_nameObject

Returns the value of attribute db_name.



6
7
8
# File 'lib/corto.rb', line 6

def db_name
  @db_name
end

Instance Method Details

#countObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/corto.rb', line 34

def count
  if ! @use_db
    return -1 
  end
  @db = SQLite3::Database.new(@db_name)
  count = @db.execute("SELECT COUNT(*) FROM urls;")
  @db.close
  
  # output is an array of arrays... so [[int]]
  count.first.first
end

#deflate(shrunk_url) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/corto.rb', line 62

def deflate(shrunk_url)
  if @use_db
    @db = SQLite3::Database.new(@db_name)
    result = @db.execute("SELECT original FROM urls WHERE url='" +shrunk_url+"'")
    (! result.first.nil?) ? result.first.first : nil
  else
    nil
  end
end

#purgeObject



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/corto.rb', line 21

def purge
  if ! @use_db
    return nil 
  end

  if File.exists?(@db_name)
    File.delete(@db_name)
  end
  @db = SQLite3::Database.new(@db_name)
  @db.execute("CREATE TABLE urls (id integer primary key, url varchar2(256), original varchar2(256));")
  @db.close
end

#shrink(url) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/corto.rb', line 46

def shrink(url)
  uri = URI::parse(url)
  return nil unless uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS
  
  if @use_db
    @db = SQLite3::Database.new(@db_name)
    count = @db.execute("SELECT COUNT(*) FROM urls WHERE url='" +url.hash.abs.to_s(36)+"'")
    if count.first.first == 0
      @db.execute("INSERT INTO urls (url, original) VALUES ('"+url.hash.abs.to_s(36)+ "', '"+url+"')")
    end
    @db.close
  end
  
  url.hash.abs.to_s(36)
end