In my Rails application I have a class that I want to initialize and then access it throughout my controllers. So the idea is that I set it via the application controller if it's not already been defined:
class ApplicationController < ActionController::Base
before_action :set_custom_class
# create an instance of customclass if doesn't exist
def set_custom_class
@custom_class ||= CustomClass.new
end
end
An example of the class:
class CustomClass
def initialize; end
def custom_method
@custom_method
end
def custom_method=(content)
@custom_method = content
end
end
If I then have a controller like:
class MyController < ApplicationController
def method_1
# set the custom_method value on my instance
@custom_class.custom_method('Some content')
# return the value I set above
@variable = @custom_class.custom_method
redirect_to :method_2
end
def method_2
# I should be able to retrieve the same value from that same instance
@variable = @custom_class.custom_method
end
end
What I'm finding is that when calling method_1
the @variable
will return my content fine, but when calling method_2
AFTER method_1 (so the custom_method for the app wide @custom_class has been set) it's returning nil.
Why isn't the instance being retained? The @custom_class
shouldn't be creating a new instance as it's already been set. So I can't understand why the value I have set gets lost when requesting it.