Skip to content

Instantly share code, notes, and snippets.

@terryfinn
Last active December 14, 2015 21:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save terryfinn/5151367 to your computer and use it in GitHub Desktop.
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…
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