开发者

Stateful Rails app. Storing data not in database

I have a Rails application, that includes chat. Everything works fine开发者_JS百科, 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?


  • 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?


You should look at Redis

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜