Created
August 28, 2014 13:01
-
-
Save claudijd/e5f3d331343e3dd71b78 to your computer and use it in GitHub Desktop.
A rough mock up of a Hash storage/retrieval container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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