How to get variable in sorcery.rb at controller

177 Views Asked by At

I am using the sorcery gem in a Rails 6 application.
I need to use variable in sorcery.rb at controller, however I do not know how to get the value.

Rails.application.config.sorcery.submodules = [:user_activation]
Rails.application.config.sorcery.configure do |config|
  config.user_config do |user|
    user.activation_token_expiration_period = 60 * 60 * 24 * 7 # <= this
  end
end

How can I get this?

2

There are 2 best solutions below

0
Ninh Le On BEST ANSWER

If you have an instance of User you can do it this way:

User.new.sorcery_config.activation_token_expiration_period
1
Deepesh On

You can keep this token expiration period in a config file instead and use it anywhere required. There are many ways you can set the config (my preferred way is):

Add a config.yml file inside config folder:

defaults: &defaults
  activation_token_expiration_period: 60 * 60 * 24 * 7
development:
  <<: *defaults
test:
  <<: *defaults
production:
  <<: *defaults

And then in application.rb file you can do like this:

APP_CONFIG = YAML.load_file('config/config.yml')[Rails.env]

And then use it anywhere in the application like this:

APP_CONFIG['activation_token_expiration_period']

So in your case you can do like this:

Rails.application.config.sorcery.configure do |config|
  config.user_config do |user|
    user.activation_token_expiration_period = APP_CONFIG['activation_token_expiration_period']
  end
end

You can set this config in any way (you might be having this already setup in your application), the primary suggestion is to use an environment variable to store this value and use it in the application wherever required.