A_toaster A_toaster - 1 month ago 5
Ruby Question

Is there a simple way to have persistent form data in SInatra? Or does it require I write form variables to a file and read them manually?

I have a form in Sinatra with 4 text fields. When the page is closed and then reopened I would like to fill the text fields with the values that were last submitted.

I am doing this currently by writing each variable to a file in the same folder, and then reading them back when the program starts. I would like to know if there is an easier way to do this.

Is there an already implemented system in Ruby/Sinatra that allows me to write form data to a file and then read it back somehow?

Answer

The best way to handle such situations in sinatra is to use sessions instead of having to write it to a file and retrieve it. Enable sessions in your configure block.

configure do
 enable :sessions
 set :session_secret, "secret"
end

in your before block

before do
  session[:user_input] ||= []
end

Then pass the user input values in the sessions object. From there it can be retrieved as long as the user sessions is active.