Class: Lich::Common::DatabaseAdapter
- Inherits:
-
Object
- Object
- Lich::Common::DatabaseAdapter
- Defined in:
- lib/common/settings/database_adapter.rb
Overview
Database adapter to separate database concerns
Instance Method Summary collapse
-
#get_settings(script_name, scope = ":") ⇒ Hash
Retrieves settings for a given script and scope.
-
#initialize(data_dir, table_name) ⇒ DatabaseAdapter
constructor
Initializes a new DatabaseAdapter instance.
-
#save_settings(script_name, settings, scope = ":") ⇒ void
Saves settings for a given script and scope.
-
#setup! ⇒ void
Sets up the database table if it does not already exist.
-
#table ⇒ Sequel::Dataset
Returns the database table object.
Constructor Details
#initialize(data_dir, table_name) ⇒ DatabaseAdapter
Initializes a new DatabaseAdapter instance.
13 14 15 16 17 18 |
# File 'lib/common/settings/database_adapter.rb', line 13 def initialize(data_dir, table_name) @file = File.join(data_dir, "lich.db3") @db = Sequel.sqlite(@file) @table_name = table_name setup! end |
Instance Method Details
#get_settings(script_name, scope = ":") ⇒ Hash
Retrieves settings for a given script and scope.
52 53 54 55 |
# File 'lib/common/settings/database_adapter.rb', line 52 def get_settings(script_name, scope = ":") entry = @table.first(script: script_name, scope: scope) entry.nil? ? {} : Marshal.load(entry[:hash]) end |
#save_settings(script_name, settings, scope = ":") ⇒ void
This method returns an undefined value.
Saves settings for a given script and scope.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/common/settings/database_adapter.rb', line 66 def save_settings(script_name, settings, scope = ":") blob = Sequel::SQL::Blob.new(Marshal.dump(settings)) if @table.where(script: script_name, scope: scope).count > 0 @table .where(script: script_name, scope: scope) .insert_conflict(:replace) .update(hash: blob) else @table.insert( script: script_name, scope: scope, hash: blob ) end end |
#setup! ⇒ void
Note:
This method is called during initialization.
This method returns an undefined value.
Sets up the database table if it does not already exist.
26 27 28 29 30 31 32 33 |
# File 'lib/common/settings/database_adapter.rb', line 26 def setup! @db.create_table?(@table_name) do text :script text :scope blob :hash end @table = @db[@table_name] end |
#table ⇒ Sequel::Dataset
Returns the database table object.
40 41 42 |
# File 'lib/common/settings/database_adapter.rb', line 40 def table @table end |