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 'sdbm'

SDBM.open 'my_database_file' do |db|
  # Add / Update One At a Time
  db['foo'] = 'a string'
  db['bar'] = '1'

  # Add / Update Many at Once
  db.update({some: 'thing', ruby: 'awesome'})

  # Get all Values
  db.each do |k,v|
    puts "Key: #{k}, Value: #{v}"
  end

  # Retrieve Specific Value
  puts db['foo']

  # See Docs for more methods http://ruby-doc.org/stdlib-2.2.3/libdoc/sdbm/rdoc/SDBM.html
end


Second we have PStore


require 'pstore'

store = PStore.new('my_database.pstore') # Create or Load my_database.pstore 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/pstore/rdoc/PStore.html
end


Lastly I describe a method using YAML which is the exact same as PStore but the file is human readable


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 - Rails

Date:May 12, 2016