Ruby - File pStore

Introduction

PStore is a core Ruby library.

It stores Ruby objects and data structures in a file.

You can reload the objects back into memory from the disk file.

This technique is known as object persistence.

Demo

require 'pstore' 

class Person #   ww w.  ja v  a 2s  .c  o  m
  attr_accessor :name, :job, :gender, :age 
end 

fred = Person.new 
fred.name = "Java" 
fred.age = 45 

laura = Person.new 
laura.name = "Json" 
laura.age = 23 


store = PStore.new("storagefile") 
store.transaction do 
  store[:people] ||= Array.new 
  store[:people] << fred 
  store[:people] << laura 
end

Here, you create a new PStore in a file called storagefile.

You can retrieve the data from the PStore database:

Demo

require 'pstore' 

class Person #  w  w w. j  ava 2s . co m
  attr_accessor :name, :job, :gender, :age 
end 

fred = Person.new 
fred.name = "Java" 
fred.age = 45 

laura = Person.new 
laura.name = "Json" 
laura.age = 23 


store = PStore.new("storagefile") 
store.transaction do 
  store[:people] ||= Array.new 
  store[:people] << fred 
  store[:people] << laura 
end 


store = PStore.new("storagefile") 
people = [] 
store.transaction do 
  people = store[:people] 
end 

# At this point the Person objects inside people can be treated 
# as totally local objects. 

people.each do |person| 
  puts person.name 
end

Result