Pulling some config variables from DB for dynamic change in Rails environment?
Is it possible to dynamically set some config variables in production.rb
using values ββfrom the database?
I am building an application for multiple tenants and each tenant has some environmental related information that needs to be set dynamically.
For example:
// production.rb
config.action_mailer.default_url_options = { :host => current_tenant.domain }
current_tenant
is a helper method defined in ApplicationHelper
so it cannot be accessedproduction.rb
Here is current_tenant
:
// application_helper.rb
def current_tenant
@current_tenant ||= Tenant.find_by(domain: Apartment::Tenant.current)
end
If not, is it possible to dynamically create secrets.yml
using DB data? Since then, I could use ENV
inproduction.rb
source to share
Perhaps you can try this instead: Create a helper method for your emails:
def build_tenant_url(route_name, *args)
opts = args.extract_options!
opts.merge!(host: @tenant ? @tenant.domain : your_domain)
#Here you can merge other options if you need to pass a token etc
Rails.application.routes_url_helpers.send(:"#{route_name}_url", *args, opts)
end
In your mailer, define @tenant
Then in your mailbox use
= link_to 'Edit', build_tenant_url(:edit_tenant, @tenant)
source to share
This setting is triggered when the application starts, so if you want the option to be controlled by some variable, that variable must be available to the Ruby code that runs at startup. There were different ways to do it.
- The script (or whatever) that starts your rails server goes through the parameter
- the value is written to a text file by some other process and re-read when the script is run
- again, but with an environment variable
For example, if you provide each tenant (user group) with its own subdomain in your application, then the subdomain name can be used as a key for the startup code to read the database and pull some data for that tenant.This subdomain will then be pushed to the application when you run it.
EDIT - having said all of this, I'm not sure if you need to change your startup config at all. Can't you just find the corresponding domain name whenever you send an email, instead of changing the defaults in the config?
source to share