13

With the following code:

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

If @q is used instead of q, the search always returns results for an empty query (""). Why is this? Is the @q variable unavailable to the do...end block?

jakeonrails
  • 1,885
  • 15
  • 37

2 Answers2

20

It depends on how the block is being called. If it is called using the yield keyword or the Proc#call method, then you'll be able to use your instance variables in the block. If it's called using Object#instance_eval or Module#class_eval then the context of the block will be changed and you won't be able to access your instance variables.

@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"

In your case, it looks like Sunspot.search is calling your block in a different context using instance_eval, because the block needs easy access to that keywords method.

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
  • 4
    And this is why `instance_eval` is evil. See also [How does instance_eval work and why does DHH hate it?](http://StackOverflow.Com/q/3071532/#3071983) – Jörg W Mittag Mar 01 '11 at 17:20
  • I am having this same problem with Sunspot. Is there a work around? – Edward Ford May 24 '11 at 15:27
  • Although littering, you can wrap your instance variable inside methods and call them inside Sunspot's search block. – the-undefined Nov 25 '11 at 04:46
  • FYI, Sunspot supports both `call` and `instance_eval`. If you pass in a block param (like in Jack Zelig's answer), then it will use `call`. Check [code reference here](https://github.com/sunspot/sunspot/blob/master/sunspot/lib/sunspot/util.rb#L98) – konyak Oct 15 '15 at 16:20
7

As Jeremy says, Sunspot executes its search DSL in a new scope.

In order to use an instance variable in the Sunspot.search block, you'll need to pass it an argument. Something like this should work (not tested):

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

See here for a better explanation: http://groups.google.com/group/ruby-sunspot/msg/d0444189de3e2725

James Hibbard
  • 16,490
  • 14
  • 62
  • 74