2

假设我想通过表单将此代码嵌入到单独的 ruby​​.rb 文件中:

print "Hello, Please enter a value:"  
var = gets.to_i  
if var == 10  
  puts "Correct"  
else  
  puts "Your answer is incorrect"  
end  

在视图中提交按钮后,用户将看到结果是正确的还是不正确的。
最好的方式是通过表单嵌入文件 ruby​​.rb,它更方便,但不是必需的。
你能想出如何让它发挥作用吗?我会很高兴从你那里得到一些奖励。

谢谢

4

1 回答 1

1

A simple way to put a basic form up as a web site is Sinatra. The following is a web app in a single file, using Sinatra.

#!/usr/bin/env ruby
require 'sinatra'

get '/' do
  erb :guess
end

post '/' do
  @guess = params[:guess].to_i
  if @guess == 10
    @message = "Correct!"
  else
    @message = "Try again..."
  end
  erb :guess
end

__END__
@@ layout
<html>
  <body>
   <%= yield %>
  </body>
</html>

@@ guess
<form action="" method="post">
  <p>Guess a number: <input type="text" name="guess"/></p>
  <p><%= @message %></p>
</form>

Install the sinatra gem and run the file. You'll see a message like

== Sinatra/1.3.3 has taken the stage on 4567

Then point your browser at http://localhost:4567/ and your app is online.

于 2012-10-07T14:11:53.517 回答