Rails - How to set global instance variables in initializers?

Trantor Liu picture Trantor Liu · May 11, 2014 · Viewed 11.2k times · Source

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?

Answer

Adilbiy Kanzitdinov picture Adilbiy Kanzitdinov · May 11, 2014

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.