Reputation: 241
I am new to rails and get stuck on this problem.
The thing I am trying to do is: I need to call service A to retrieve an idA and then I use idA to perform other actions. my actions in the controller is something like
class SomeController < ApplicationController
def someAction
idA = getIdAfromServiceA(config)
doSomethingElseToServiceB(idA)
end
end
Since the result from serviceA only depends on config, once the config is loaded, idA should not change. Therefore I want to cache idA.
I tried to use instance variable to cache it, no luck("getIdAfromServiceA is called is printed" on every request)
class SomeController
def getIdAfromServiceA(config)
@IdA ||= getIdAfromServiceAviaHTTP(config)
end
private
def getIdAfromServiceAviaHTTP(config)
puts "getIdAfromServiceAviaHTTP is called"
#make some http call
end
end
I also tried to put it in application.rb
to cache it on start up. it shows error: undefined method 'getIdAfromServiceAviaHTTP' for SomeHelper:Module (NoMethodError)
module MyProject
class Application < Rails::Application
config.load_defaults 5.1
require_relative 'relativePathToSomeHelperModule'
config.idA = SomeHelper.getIdAfromServiceAviaHTTP(config)
end
end
So my question is, what's a good way to achieve this ? I've been googling for a while but end up in vain. Could you help me with it ? Thanks !
Upvotes: 1
Views: 65
Reputation: 2747
Create a ruby file in under /config/initializers/
and put that code there.
Option 1:
# config/initializers/ida_from_api.rb
IDA = SomeHelper.getIdAfromServiceAviaHTTP(config)
You can then use IDA
through out the application.
Option 2:
# config/initializers/ida_from_api.rb
Rails.configuration.idA = SomeHelper.getIdAfromServiceA(config)
You can then use Rails.configuration.idA
through out the application. Check Custom configuration for more details.
FYI - files under initializers
loaded at the time of application startup.
Upvotes: 4