Using instance variables inside the Sunspot.search method

676 views
Skip to first unread message

Matt Coneybeare

unread,
May 8, 2011, 10:48:29 PM5/8/11
to ruby-s...@googlegroups.com
First, thanks for the excellent gem and support group!

I am having trouble understanding why I am can't use instance variables in the Sunspot.search method.
 

Using this code, @search_term ends up being nil and @page ends up being 0 (nil)
============================
@search_term = params[:id]
@page = params[:page] || 1

search = Sunspot.search([Sound, UserSound]) do
  keywords @search_term
  with :published, true
  paginate :page => @page, :per_page => Sound.per_page
end
=============================



If I ditch the instance variables and use a local variable, everything is as expected
=============================
search_term = params[:id]
page = params[:page] || 1

search = Sunspot.search([Sound, UserSound]) do
  keywords search__term
  with :published, true
  paginate :page => page, :per_page => Sound.per_page
end
=============================



Can anybody explain why this is?

Thanks,
Matt

Matthew A. Brown

unread,
May 9, 2011, 7:46:40 AM5/9/11
to ruby-s...@googlegroups.com
Hi Matt,

The reason for this is that in order to provide the DSL for building
the search (methods like 'keywords', 'with', and 'paginate' in your
example), Sunspot has to change the evaluation context of the search
block. Local variables are always retained inside blocks (blocks are
closures), and Sunspot does some Ruby dark magic so that you can still
access methods from the calling context when you're inside the search
DSL; but instance variables are very difficult to expose and so
Sunspot doesn't attempt it.

Sunspot does allow you to provide a block parameter to the DSL block,
in which case the parameter exposes the DSL, and Sunspot doesn't
change the calling context; so, the following would work:

search = Sunspot.search([Sound, UserSound]) do |query|
query.keywords @search_term
query.with :published, true
query.paginate :page => @page, :per_page => Sound.per_page
end

Hope that clears things up.
Mat

> --
> You received this message because you are subscribed to the Google Groups
> "Sunspot" group.
> To post to this group, send email to ruby-s...@googlegroups.com.
> To unsubscribe from this group, send email to
> ruby-sunspot...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/ruby-sunspot?hl=en.
>

Reply all
Reply to author
Forward
0 new messages