Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Sinatra,干燥和范围界定_Ruby_Sinatra - Fatal编程技术网

Ruby Sinatra,干燥和范围界定

Ruby Sinatra,干燥和范围界定,ruby,sinatra,Ruby,Sinatra,我正在寻找干燥我的Sinatra应用程序的方法,并且遇到了一些范围问题——特别是,助手和Sinatra函数在我的处理程序中不可用。有人能告诉我是否有办法修复这个代码,更重要的是,发生了什么 多谢各位 require 'sinatra' require 'pp' helpers do def h(txt) "<h1>#{txt}</h1>" end end before do puts request.path end def r(url, ge

我正在寻找干燥我的Sinatra应用程序的方法,并且遇到了一些范围问题——特别是,助手和Sinatra函数在我的处理程序中不可用。有人能告诉我是否有办法修复这个代码,更重要的是,发生了什么

多谢各位

require 'sinatra'
require 'pp'

helpers do
  def h(txt)
    "<h1>#{txt}</h1>"
  end
end

before do
  puts request.path
end


def r(url, get_handler, post_handler = nil)
  get(url){ get_handler.call } if get_handler
  post(url){ post_handler.call } if post_handler
end


routes_composite_hash = {
    '/' => lambda{ h('index page'); pp params }, #can't access h nor params!!!
    '/login' => [lambda{'login page'}, lambda{'login processing'}],
    '/postonly' => [nil, lambda{'postonly processing'}],
}

routes_composite_hash.each_pair do |k,v|
  r(k, *v)
end
需要“sinatra”
需要“pp”
帮手
def h(txt)
“#{txt}”
结束
结束
在做之前
放置请求路径
结束
DEFR(url,获取处理程序,发布处理程序=nil)
get(url){get\u handler.call}如果get\u handler
post(url){post_handler.call}if post_handler
结束
路由\组合\哈希={
“/”=>lambda{h('index page');pp params},#无法访问h或params!!!
“/login'=>[lambda{'login page'},lambda{'login processing'}],
'/postonly'=>[nil,lambda{'postonly processing'}],
}
路由组合散列。每个对都有k,v|
r(k,*v)
结束

您在
帮助程序中定义的方法确实如此。。end
块仅在路由、过滤器和视图上下文中可用,因此,由于您没有在其中任何一个上下文中使用它们,因此它将不起作用。lambda保留执行上下文,这意味着在hash
{'/'=>lambda{h}..}
中,上下文是
main
,但在
get
方法中,上下文会更改,并且帮助程序仅在此上下文中可用

为了实现您想要做的事情(尽管我建议您避免这样做),您可以在应用程序文件本身中将helpers定义为lambda。在您的情况下,它将是:

def h(txt) 
  "<h1>#{txt}</h1>"
end

# And then the rest of the methods and the routes hash
def h(txt)
“#{txt}”
结束
#然后是其余的方法和路由散列
这样,
h
方法就位于
main
对象的上下文中,因此将在整个对象中可见。

有趣

这样做:

def r(url, get_handler, post_handler = nil) 
  get(url, &get_handler) if get_handler
  post(url, &post_handler) if post_handler
end


routes_composite_hash = {
    '/' => lambda{ h('index page'); pp params },
    '/login' => [lambda{'login page'}, lambda{'login processing'}],
    '/postonly' => [nil, lambda{'postonly processing'}],
}

routes_composite_hash.each_pair do |k,v|
  r(k, *v)
end

如上所述,您在
main
上下文中调用get和post处理程序。这只是将发送的lambda转换为一个块,并将其传递给所需的方法。

必须有一种方法在指定上下文中对块求值,但我无法这样做。感谢您的解释,真的很好,我没有意识到您可以直接传递该块以获取/发布!非常感谢!