【问题标题】:@instance_variable not available inside a ruby block?@instance_variable 在红宝石块内不可用?
【发布时间】:2011-07-06 05:57:51
【问题描述】:

使用以下代码:

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 块不可用吗?

【问题讨论】:

  • 你试过用ruby -W2运行吗?
  • 非常感谢@jakeonrails 提出这个问题,我为这个问题苦苦挣扎了好几个小时。答案也很好。

标签: ruby scope instance block


【解决方案1】:

这取决于块的调用方式。如果使用yield 关键字或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 方法。

【讨论】:

  • 这就是为什么instance_eval 是邪恶的。另见How does instance_eval work and why does DHH hate it?
  • 太阳黑子也有同样的问题。有解决办法吗?
  • 虽然乱扔垃圾,但您可以将实例变量包装在方法中并在 Sunspot 的搜索块中调用它们。
  • 仅供参考,Sunspot 同时支持callinstance_eval。如果您传入一个块参数(如 Jack Zelig 的回答),那么它将使用 call。检查code reference here
【解决方案2】:

正如 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    相关资源
    最近更新 更多