Stateful Rails app. Storing data not in database

1.3k views Asked by At

I have a Rails application, that includes chat. Everything works fine, but now I want to store the last 50 chat messages somewhere. I need it to show the last messages if a page is reloaded. I don't want to use database. It would be good to store it in some kind of array, but Rails is stateless. I'm looking to make it a little more stateful with your help.

Thx

UPD:

I've found PStore ( http://www.ruby-doc.org/stdlib/libdoc/pstore/rdoc/classes/PStore.html ). It looks pretty good for me, doesn't it?

2

There are 2 answers

2
Phrogz On BEST ANSWER
  • Your simplest answer is Marshal, since it is part of the Ruby core. Just dump your actual array to disk as a binary file and read it back as you need.

    MYDB = 'mydb.marshal'
    
    # Write to disk
    last_50 = [ "foo", "bar" ]
    File.open( MYDB, 'wb' ){ |f| f << Marshal.dump( last_50 ) }
    
    # Load from disk
    last_50 = Marshal.load( File.open( MYDB, 'rb' ){ |f| f.read } )
    p last_50
    #=> ["foo", "bar"]
    
  • If you want the file format to be human-readable, try YAML (part of the Ruby standard library) or JSON as a gem. Both are plain-text file formats that you can dump to file, see, and load again.

  • You say you "don't want a database", but you don't say why. Do you know that SQLite has its database in a single file, is easy to install, and is fast and lightweight?

2
danivovich On

You should look at Redis