现在的位置: 首页 > 综合 > 正文

ruby sinatra 简单例子

2019年07月23日 ⁄ 综合 ⁄ 共 830字 ⁄ 字号 评论关闭

server.rb

require 'sinatra'

#前置过滤器
before do
  puts 'before process'
end

#后置过滤器
after do
  puts 'after process'
end

#找不到页面调用的逻辑
not_found do
  '<h1>404 you know!</h1>'
end

get '/' do
  '<h1>Hello World</h1>'
end

#渲染views/index.erb模板
get '/show' do
  erb :index
end

#渲染views/success.erb模板
post '/submit' do
  @email = 'hr@163.com'
  @email2 = params['email']
  @url = request.url
  erb :success
end

在server.rb文件的所在目录中创建目录views,

然后,在views中,创建如下文件

index.erb

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' />
  <title>提交表单</title>
</head>
<body>
<h1>submit you form</h1>
<form method="post" action="/submit">
you email : <input type="text" name="email"/>
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>

success.erb

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Ruby test</title>
</head>
<body>
<h1>this is success page</h1>
<h2>HR的邮箱:<%=@email %></h2>
<h2>你的邮箱:<%=@email2 %></h2>
<h2>you url <%=@url %></h2>
</body>
</html>

抱歉!评论已关闭.