Rails - 如何在初始化器中设置全局实例变量?

时间:2014-05-11 03:46:01

标签: ruby-on-rails controller initializer

我使用的是predictor宝石。我在initializers/predictor.rb

中初始化了推荐人
require 'course_recommender'    

recommender = CourseRecommender.new

# Add records to the recommender.
recommender.add_to_matrix!(:topics, "topic-1", "course-1")
recommender.add_to_matrix!(:topics, "topic-2", "course-1")
recommender.add_to_matrix!(:topics, "topic-1", "course-2")

然后我想在CourseController中使用推荐器,如下所示:

class CourseController < ApplicationController
  def show
    # I would like to access the recommender here.
    similiar_courses = recommender.similarities_for("course-1")
  end
end

我如何将recommender设置为应用程序控制器变量,以便我可以在控制器中访问它?

3 个答案:

答案 0 :(得分:40)

initilizers/predictor.rb中,您应将推荐人定义为:

recommender = CourseRecommender.new

但是:

  

:: Recommender = CourseRecommender.new

这样,您可以在应用程序的整个范围内定义常量,而不是定义局部变量。在初始值设定项和控制器中,您可以Recommender访问它。

答案 1 :(得分:4)

我解决了这个问题。但是,我没有设置全局实例,而是使用Singleton模式。

以下是代码:

# lib/course_recommender.rb
require 'singleton'
class CourseRecommender
  include Predictor::Base
  include Singleton
  # ...
end

# initializers/predictor.rb
@recommender = CourseRecommender.instance

# Add records to the recommender.
@recommender.add_to_matrix!(:topics, "topic-1", "course-1")
@recommender.add_to_matrix!(:topics, "topic-2", "course-1")
@recommender.add_to_matrix!(:topics, "topic-1", "course-2")

# controllers/course_controller.rb
require 'course_recommender'
class CourseController < ApplicationController
  def show
    similiar_courses = CourseRecommender.instance.similarities_for("course-1")
  end
end

答案 2 :(得分:2)

我不熟悉那个gem,但看起来你应该在ApplicationController中使用你的代码。

ApplicationController中的

@recommender = CourseRecommender.new

# Add records to the recommender.
@recommender.add_to_matrix!(:topics, "topic-1", "course-1")
@recommender.add_to_matrix!(:topics, "topic-2", "course-1")
@recommender.add_to_matrix!(:topics, "topic-1", "course-2")

然后在你的控制器中:

class CourseController < ApplicationController
  def show
    # I would like to access the recommender here.
    similiar_courses = @recommender.similarities_for("course-1")
  end
end