Run Ruby file from html form submit

柔情痞子 提交于 2020-01-06 06:54:15

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/47240589/run-ruby-file-from-html-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!