문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top