ruby-on-rails 如何在初始化器中设置全局示例变量?

pnwntuvh  于 2022-11-19  发布在  Ruby
关注(0)|答案(3)|浏览(156)

我使用的是predictor gem。我在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设置为应用程序控制器变量,以便在控制器中访问它?

a7qyws3x

a7qyws3x1#

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

recommender = CourseRecommender.new

而是作为:

Recommender = CourseRecommender.new

这样你就可以在整个应用程序的作用域中定义一个常量,而不是定义一个局部变量。2在你的初始化器和控制器中,你可以用Recommender的方式访问它。

xxls0lw8

xxls0lw82#

我解决了这个问题,但是我没有设置一个全局示例,而是使用了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
g52tjvyc

g52tjvyc3#

我不熟悉这个gem,但是看起来您应该在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

相关问题