Mustermann::URL 中的编译错误



我有一个Sinatra驱动的博客,方法如下:

module Tir
module Blog
class Article
def url
[Tir::Config.domain, meta('relative_path')].join
end
end
end
end

在文章实例上调用 this 会输出文章的完整 URI,如下所示:

"http://example.com/2018/07/08/test-article"

了不起的穆斯特曼给了我以下错误:

Mustermann::CompileError:捕获名称不能为空:"/http://example.com/2018/07/08/test-article">

  1. 为什么它会在字符串的开头插入正斜杠?
  2. 为什么它如此严格 wrt 生成的字符串甚至不是 Sinatra 路由?
  3. 如何摆脱这个问题?

谢谢。

编辑29.08.2018:事实证明,Sinatra/Mustermann阻止了这些字符串,因为它们路线。我生成动态文章路由的主要方法是:

articles = []
Dir.glob('articles/*.mdown') do |file|
article = initialize_article file
if article.ready?
get("/#{article.url}") do
erb :'articles/article',
:locals => { :article => article },
:layout => :'articles/layout_article'
end
articles << article
end
end

改进后的版本在get块中使用了不同的方法:

#articles.rb
articles = []
Dir.glob('articles/*.mdown') do |file|
article = initialize_article file
if article.ready?
get("/#{article.relative_path}") do
erb :'articles/article',
:locals => { :article => article },
:layout => :'articles/layout_article'
end
articles << article
end
end

方法定义:

#blog.rb
def relative_path
meta('relative_path')
end
def url
[Tir::Config.domain, meta('relative_path')].join
end

因此,现在url方法永远不会在路由中调用,只会在其中一个视图中的文章对象上调用 - 因此没有错误。

Sinatra路由助手和Mustermann本身不接受完整的URL作为模式,只接受路径 - 你不能在其中放置主机名。Mustermann 的自述文件提供了支持的模式类型的完整列表,所有示例都显示了路径。正如您所说的,"限制性"行为是正常的,因为它不是一个通用的模式匹配库 - 它专门用于处理 URL 路径。

如果您不想为 Sinatra 路由指定主机名,您可以使用可选的host_name参数来实现。

get '/2018/07/08/test-article', host_name: 'example.com' do
erb :article  
end

如果要使用 Mustermann 进行自定义匹配,文档中列出的uri-template模式类型适用于完整的 URL。您必须安装 gem 并掌握略有不同的模式语法mustermann-contrib

irb(main):011:0> require 'mustermann'
=> true
irb(main):012:0> pattern = Mustermann.new("http://example.com/2018/07/08/{slug}", type: 'uri-template')
=> #<Mustermann::Template:"http://example.com/2018/07/08/{slug}">
irb(main):013:0> pattern.match "http://example.com/2018/07/08/test-article"
=> #<MatchData "http://example.com/2018/07/08/test-article" slug:"test-article">

最新更新