3 Built-In Methods For Simple File Based Storage In Ruby Or Rails

Posted By Weston Ganger

Sometimes a full SQL database or even SQLite is too much for the job. Did you know ruby has at lots of other built-in methods for file storage? In this article I will describe the best 3 in my opinion.

First is SDBM which is a simple file-based key-value store. It only stores string keys and string values.

require 'yaml/store'

store = YAML::Store.new('my_database.yaml') # Create or Load my_database.yaml file

# Get Store Data
my_var = store.transaction{store[:my_var]}

# Save Data
store.transaction do
  store[:foo] = 'bar'
  store[:greeting] = ['Hello','World']
  store[:amount] = 1.56
  store[:last_accessed] = Time.now

  # Save Changes
  store.commit

  # Abort Changes
  store.abort 

  # Read more at the docs at http://ruby-doc.org/stdlib-2.2.3/libdoc/yaml/rdoc/YAML/Store.html
end

Related External Links:

Article Topic:Software Development - Ruby / Rails

Date:May 12, 2016