Reputation: 9126
I was using the predictor gem. I initialized the recommender in 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")
And then I wanted to use the recommender in the CourseController like this:
class CourseController < ApplicationController
def show
# I would like to access the recommender here.
similiar_courses = recommender.similarities_for("course-1")
end
end
How could I set recommender
as an application controller variable so I could access it in the controllers?
Upvotes: 19
Views: 14283
Reputation: 658
In your initilizers/predictor.rb
you shall define your recommender not as:
recommender = CourseRecommender.new
but as:
Recommender = CourseRecommender.new
this way you define a constant throughout the scope of your application, instead of defining a local variable. In your initializer and controller you access it as Recommender
.
Upvotes: 47
Reputation: 9126
I solve the problem. But instead of setting a global instance, I use the Singleton pattern.
Here's the code:
# 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
Upvotes: 7
Reputation: 16728
I am not familiar with that gem, but it seems like you should have your code in ApplicationController.
in 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")
and then in your controler:
class CourseController < ApplicationController
def show
# I would like to access the recommender here.
similiar_courses = @recommender.similarities_for("course-1")
end
end
Upvotes: 1