我如何通过表单嵌入 ruby​​.rb 文件,以执行 ruby​​.rb 并且结果在视图中可见 [英] How do I embed ruby.rb file via form in a way that ruby.rb would be executed and results visible in view

查看:51
本文介绍了我如何通过表单嵌入 ruby​​.rb 文件,以执行 ruby​​.rb 并且结果在视图中可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

let's say I want to embed this code via form in a separate ruby.rb file:

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

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

After the submit button in view user will see either results are correct or incorrect.
In a best way file ruby.rb would be embedded via form, it's more convinient, but not essential.
Could you think of how to make it work? I would be very nice to have some incentives from you.

谢谢

推荐答案

一种将基本表单设置为网站的简单方法是 辛纳特拉.以下是使用 Sinatra 的单个文件中的网络应用.

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>

安装 sinatra gem 并运行该文件.您会看到类似

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

== Sinatra/1.3.3 has taken the stage on 4567

然后将您的浏览器指向 http://localhost:4567/,您的应用就在线了.

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

这篇关于我如何通过表单嵌入 ruby​​.rb 文件,以执行 ruby​​.rb 并且结果在视图中可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆