Search code examples
rubyhtmlformssinatra

Run Ruby file from html form submit


I have a Ruby program that reads a file and returns a certain output. I have to now create a web app of this program using Sinatra. I created a form with all the file options and I want to now run that Ruby code with that selected file from the form after the submit button is pressed.

Basically, I’m not sure how to get this external Ruby program to run with the the filename that was selected by the user from the HTML form.

The Ruby program (example.rb) starts with the definition def read_grammar_defs(filename).

// sinatra_main.rb

require 'sinatra'
require 'sinatra/reloader' if development? #gem install sinatra-contrib
require './rsg.rb'

get '/' do
 erb :home
end

post '/p' do
  //call program to read file with the parameter from form 
end




// layout.erb

<!doctype html>
<html lang="en">
<head>
  <title><%= @title || "RSG" %></title>
  <meta charset="UTF8">
</head>
<body>
 <h1>RubyRSG Demo</h1>
 <p>Select grammar file to create randomly generated sentence</p>
 <form action="/p" method="post">
  <select name="grammar_file">
      <option value="Select" hidden>Select</option>
      <option value="Poem">Poem</option>
      <option value="Insult">Insult</option>
      <option value="Extension-request">Extension-request</option>
      <option value="Bond-movie">Bond-movie</option>
 </select>
 <br><br>
 </form>
<button type="submit">submit</button>
<section>
 <%= yield %>
</section>
</body>
</html>

Solution

  • The easiest way is as follows:

    1. Package the example.rb code into a class or module like so:

      class FileReader
        def self.read_grammar_defs(filename)
          # ...
        end
      end
      
    2. require the file from your sinatra server

    3. Inside the post action, read the params and call the method:

      post '/p' do
        @result = FileReader.read_grammar_defs(params[:grammar_file])
        erb :home
      end
      

    With this code, after submitting the form, it would populate the @result variable and render the :home template. Instance variables are accessible from ERB and so you could access it from therer if you wanted to display the result.

    This is one potential issue with this, though - when the page is rendered the url will still say "your_host.com/p" and if the user reloads the page, they will get a 404 / "route not found" error because there is no get "/p" defined.

    As a workaround, you can redirect '/' and use session as described in this StackOverflow answer or Sinatra' official FAQ to pass the result value.