Skip to content Skip to sidebar Skip to footer

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

Solution 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.


Post a Comment for "Run Ruby File From Html Form Submit"