I've seen posts where the suggestion was to create an initializer or create a config.after_initialize
block in the config/application.rb
file; however, this doesn't properly work for me because I'm relying on Rails credentials.
For example, I have a class called SlackBot
that basically sends a message to our slack channel. I'd like to create an initializer that sends a message once the rails s
command is run, but the config.after_initialize
doesn't actually work since the SlackBot
class pulls creds from Rails.application.credentials
I get the following error when trying to do this:
ubuntu@bf29b8edfeea:~/myapp$ rails s --binding 0.0.0.0 -p 80
=> Booting Puma
=> Rails 6.1.4.4 application starting in development
=> Run `bin/rails server --help` for more startup options
Exiting
/usr/local/bundle/gems/activesupport-6.1.4.4/lib/active_support/message_verifier.rb:176:in `verify': ActiveSupport::MessageVerifier::InvalidSignature (ActiveSupport::MessageVerifier::InvalidSignat
ure)
from /usr/local/bundle/gems/activesupport-6.1.4.4/lib/active_support/message_encryptor.rb:154:in `decrypt_and_verify'
from /usr/local/bundle/gems/activesupport-6.1.4.4/lib/active_support/messages/rotator.rb:22:in `decrypt_and_verify'
from /home/ubuntu/myapp/app/helpers/user_helper.rb:19:in `decrypt_data'
The only way I can get rid of this error of course is by removing the custom initializer.
Is there a way that I can call an initializer or method after rails is fully initializer, perhaps as the last step that runs?
CodePudding user response:
According to The Rails Initialization Process of the Rails official reference, the last file to be executed in the initialization sequence is config/environment.rb
(Note that although the reference states the last one is config/application.rb
, the file should have been in default require-d in the earlier process).
In Rails 6 (or maybe earlier ones, too?), the last line in config/environment.rb
is
Rails.application.initialize!
So, if you write your own statements after the line in the file config/environment.rb
, your Rails app must have been fully initialized by the time your statements are executed.