msc
msc

Reputation: 67

How to print to web page using Ruby and Sinatra

I'm calling a ruby function in a post method and I'm trying to output the contents from the function to the web page but it prints the output in my console instead. How do I get it to print to the page?

I've tried

<%=rsg(params[:grammar_file])%> inside an erb file

and

rsg(params[:grammar_file])

inside of the post method and both just print to the console

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

get '/' do
 erb :index

end

post '/' do
rsg(params[:grammar_file])
erb :index

end




<% title = "RANDOM SENTENCE GENERATOR" %>
<!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="/" 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>
<input type="submit" value="submit">
</form>

<section>
  <p>Here</p>
  <p><%= rsg(params[:grammar_file])%></p>

</section>


</body>
</html>

Upvotes: 0

Views: 1053

Answers (1)

three
three

Reputation: 8478

You need to tell your template what to do with the params.

This is what is happening:

post '/' do
  rsg(params[:grammar_file])
  # your rsg method produces some output. I guess you have a line the `puts` your params to stdout somewhere. Instead you should redirect the output into the template.
  erb :index
end

Like this:

post '/' do
  erb :index, :locals => {:rsg => rsg(params[:grammar_file])}
end

Then, in your :index template you have a line like:

<%=rsg%>

To output the generated String.

The problem might also be that you're tryng to return a puts statement instead of the plain string:

def rsg(p)
  puts "I love my daily #{p}. Good luck to you"
end

This will just print to the console and nothing else (true to be precise)

Better:

def rsg(p)
  "I love my daily #{p}. Good luck to you"
end

Here you will just return the String from your method and calling rsg("sandwich") will return:

# => "I love my daily sandwich. Good luck to you"

Upvotes: 0

Related Questions