20小时学会编程 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

示例代码讲解

应用1项目所在地址https://github.com/first20hours/monograph

我们启动应用1,我们把目录定位到/samples/monograph,执行下面的命令:

~/samples/monograph$ ruby application.rb

点击 访问测试 按钮,即可看到页面效果。

现在我们主要讲解应用1monograph下的application.rb文件:

require 'rubygems'
require 'sinatra'
require 'rack-canonical-host'

set :public, Proc.new { File.join(root, "_site") }
# use Rack::CanonicalHost, 'domain.com'

# Added headers for Varnish
before do
  response.headers['Cache-Control'] = 'public, max-age=31556926' # 1 year
end

require 是请求应用中需要的框架文件,set:public 设置项目文件的根目录_site,要使用HTTP缓存,必须正确地设定消息头response.headers['Cache-Control'],核心提示: 在前置过滤器中设定缓存.

# Index handler
get '/?' do
  File.read("_site/index.html")
end

# Feed handler
get '/feed/?' do
  File.read("_site/rss.xml")
end

get '/robots.txt' do
  File.read("_site/robots.txt")
end

## Post handler

get '/*/?' do
    File.read("_site/#{params[:splat][0]}/index.html")
end

上面的代码,都是路由的处理程序,我们先请求'/?'路由匹配,如果请求路径成功,将使用ruby下File 类和read()方法,读取返回的页面。

特别提示:get '/*/?' 访问此路由下,我们使用路由范式也可以包含通配符参数, 可以通过params[:splat]接收参数,返回的是数组,所以我们需要在接收参数改成params[:splat][0],这样就可以改变参数。

## Error handler

not_found do
  File.read("_site/error/index.html")
end

error do
  File.read("_site/error/index.html")
end

错误处理在与路由和前置过滤器相同的上下文中运行,当一个 Sinatra::NotFound 错误被抛出的时候, 或者响应状态码是404not_found 处理器会被调用,error 处理器,在任何路由代码块或者过滤器抛出异常的时候会被调用。 异常对象可以通过sinatra.error Rack 变量获得。