Read and write data in a ruby script after __END__. Reading data from the DATA constant is easy, but writing to it isn't as simple. The trick is to ask DATA for its position in the file with DATA.pos. Whatever DATA.pos returns needs to be save to a variable and used to seek back to this position when writing to the file. RubySourceDataStore::Dat…
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
module RubySourceDataStore | |
class DataStore | |
DEFAULT_OPTIONS = { | |
auto_save: true, | |
serializer_name: :YAML | |
} | |
def initialize(data_file_handler, options = {}) | |
@data = data_file_handler | |
@data_pos = data_file_handler.pos | |
DEFAULT_OPTIONS.merge(options).each_pair do |key, value| | |
self.instance_variable_set("@#{key}", value) if DEFAULT_OPTIONS.keys.include?(key) | |
end | |
end | |
def get(key) | |
data_store[key] | |
end | |
def set(key, value) | |
@data_store[key] = value | |
save if auto_save? | |
end | |
def save | |
File.open(@data, 'r+') do |file| | |
file.seek(@data_pos, IO::SEEK_SET) | |
file.write(serializer.dump(data_store)) | |
end | |
end | |
private | |
def serializer | |
@serializer ||= Kernel.const_get(@serializer_name) | |
end | |
def auto_save? | |
true if @auto_save | |
end | |
def data_store | |
@data_store ||= File.open(@data, 'r') do |file| | |
file.seek(@data_pos, IO::SEEK_SET) | |
serializer.load(file.read) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment