Question

How to create a common variable which can be read and changed from all methods of Ruby on Rails controller? My real code:

require 'yaml' 

class Es1Controller < ApplicationController
def common_variables
    @questions = YAML.load_file(File.join(Rails.root, "/app/assets/es_data/questions.yml"))
    @object = Hash.new
    @object[:next_question] = 1
    @object[:parameters] = Hash.new
end

def start
    puts @questions
end

def save_parameter
    @parameter = params.except(:action, :controller, :commit, :utf8)
    (@object[:parameters]).merge!(@parameter)
    show_question
end

def show_question
    @question = @questions[@object[:next_question]]
    @object[:next_question] = @questions[@object[:next_question]]["next_question"]
    respond_to do |format|
        format.js   { render 'show_question' }
        format.json { render json: @question }
    end
end

def show_result
end
end

My index page calls for "start" method, but there is no value on @questions variable.

Was it helpful?

Solution

Thanks @BroiSatse and @Stefan for their comments.

"For every single request the new instance of controller is created, so the instance variable set in one request won't be available on the other. You might won't to create a class variable, but then it will be global to all users. Most likely look into using session to store this data."

guides.rubyonrails.org/action_controller_overview.html#session

OTHER TIPS

You should make a class that stores this info permanently

class CommonVariable
  def data
    # @questions = YAML.load_file(File.join(Rails.root, "/app/assets/es_data/questions.yml"))
    # Instead here just have the data live on the server.. don't use the yaml. that'll help server weight in the long run..
    # @object = Hash.new
    # @object[:next_question] = 1
    # @object[:parameters] = Hash.new
    # I'm not sure what these do, but just set up your data the way you want so you can call CommonVariable.data
  end
end

Then whenever you need it in your app, call :

CommonVariable.data

Or you can use custom methods to extrapolate that info should you need it.. I think this approach would work with the most server weight.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top