Skip to content

Instantly share code, notes, and snippets.

@claudijd
Created August 28, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claudijd/e5f3d331343e3dd71b78 to your computer and use it in GitHub Desktop.
Save claudijd/e5f3d331343e3dd71b78 to your computer and use it in GitHub Desktop.
A rough mock up of a Hash storage/retrieval container
require 'sqlite3'
require 'digest'
class Hasher
def self.md5(file_name)
::Digest::MD5.file(file_name).hexdigest
end
end
class HashDB
def initialize(database_name)
if File.exists?(database_name)
@db = ::SQLite3::Database.open(database_name)
else
@db = ::SQLite3::Database.new(database_name)
@db.create_schema
end
end
def create_schema
@db.execute <<-SQL
create table hashes (
hash varchar(30),
name varchar(30)
);
SQL
end
def add_hash(hash, name)
# Prevent the adding of duplicate hashes
unless get_name(hash).nil?
existing_name = get_name(hash)
raise "The hash #{hash} already exists and is mapped to #{existing_name}"
end
@db.execute "insert into hashes values ( ?, ? )", [hash, name]
end
def get_name(hash)
names = []
@db.execute( "select * from hashes where hash like ( ? )", [hash] ) do |row|
names << row[1]
end
return names.first
end
end
hash_db = HashDB.new("hash_database.sql3")
hash_db.create_schema
name = "pony"
file = "test.out"
hash = Hasher.md5(file)
hash_db.add_hash(hash, name)
hash_db.get_name(hash)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment