@instance_variable在ruby块内不可用?

使用以下代码:

def index @q = "" @q = params[:search][:q] if params[:search] q = @q @search = Sunspot.search(User) do keywords q end @users = @search.results end 

如果使用@q而不是q,则搜索始终返回空查询(“”)的结果。 为什么是这样? @q变量是否对do … end块不可用?

这取决于块的调用方式。 如果使用yield关键字或Proc#call方法Proc#call ,那么您将能够在块中使用实例变量。 如果使用Object#instance_evalModule#class_eval调用它,则块的上下文将被更改,您将无法访问实例变量。

 @x = "Outside the class" class Test def initialize @x = "Inside the class" end def a(&block) block.call end def b(&block) self.instance_eval(&block) end end Test.new.a { @x } #=> "Outside the class" Test.new.b { @x } #=> "Inside the class" 

在您的情况下,看起来Sunspot.search使用instance_eval在不同的上下文中调用您的块,因为该块需要轻松访问该keywords方法。

正如Jeremy所说,Sunspot在新范围内执行其搜索DSL。

为了在Sunspot.search块中使用实例变量,您需要传递一个参数。 这样的东西应该工作(没有测试):

  @q = params[:search][:q] if params[:search] @search = Sunspot.search(User) do |query| query.keywords @q end @users = @search.results 

有关更好的说明,请参阅此处: http : //groups.google.com/group/ruby-sunspot/msg/d0444189de3e2725