0

我收到以下错误...

pry("serp")> session[self.to_sym] = "closed"
NameError: undefined local variable or method `session' for "serp":String

...当我尝试从 String 类的猴子补丁中设置会话变量时。(这是必要的,以便我可以跟踪延迟工作中的工作进度,以便仅在准备好时加载我的搜索结果。)

如何在那里设置会话变量?还是有更好的解决方案?

我的代码...

/config/initializers/string.rb

class String
  def multisearch
    result = PgSearch.multisearch(self)
    session[self.to_sym] = "closed"
    return result
  end
end

/app/views/searches/show.html.haml

- if @term.present? && session[@term.to_sym] == "open"
  %h1 Search In Progress
  # then show spinning wheel animation etc
- else
  %h1 Search Results
  = form_tag search_path, :method => :get do
    = text_field_tag "term", "Search term"
    = submit_tag "Search"
  - unless @results.blank?
    # then show the search results etc

**/app/views/layouts/application.html.haml:

!!!
%html
  %head
    - if @term.present? && session[@term.to_sym] == "open"
      %meta{:content => "5", "http-equiv" => "refresh"}/

/app/controllers/searches_controller.rb

class SearchesController < ApplicationController
  respond_to :html
  filter_access_to :all  
  def show
    if @term = params[:term]
      session[@term.to_sym] = "open"
      @results = @term.delay.multisearch
      # other stuff...
    end
  end
end
4

2 回答 2

0

答案是停止与 Ruby 的 OO 特性作斗争,并构建一个可以拥有我需要访问的所有内容的搜索模型。

/app/models/search.rb

class Search < ActiveRecord::Base
  serialize :results
  def multisearch
    results = PgSearch.multisearch(self.term).to_a
    self.update_attributes :results => results, :status => "closed"
    return results
  end  
end

** /app/controllers/searches_controller.rb**:

class SearchesController < ApplicationController  
  respond_to :html
  def show
    if params[:term].present?
      @search = Search.find_or_create_by_term(params[:term])
      if @search.status.blank?
        @search.delay.multisearch
        @search.status = "open"
        @search.save
      elsif @search.status == "closed"
        @search.update_attributes :status => nil
      end
    end
  end
end

/app/views/searches/show.html.haml

- if @search.present? && @search.status == "open"
  # progress bar etc
- else
  = form_tag search_path, :method => :get do
    = text_field_tag "term", "Search term"
    = submit_tag "Search"
- if @search.present? && @search.status.nil?
  - unless @search.results.blank?
    # show the search results

/app/views/layouts/application.html.haml

- if @search.present? && @search.status == "open"
  %meta{:content => "5", "http-equiv" => "refresh"}/
于 2013-03-28T03:50:35.157 回答
0

将会话作为参数传递。

class String
  def multisearch session
    result = PgSearch.multisearch(self)
    session[self.to_sym] = "closed"
    return result
  end
end

然后

@term.delay.multisearch(session)
于 2013-03-27T12:06:38.833 回答