Thomas
Thomas

Reputation: 622

Config vars with multiple values

In my Rails application I have a feature that I only want to open to users that are logged in with a certain e-mail (We use Devise for user authentication). I have a method to check if a user is current_user.is_privileged?

def is_privileged?
 Settings.privileged_users.include?(email)
end 

In config/settings/test.yml I set the privileged users as:

privileged_users: ['[email protected]', '[email protected]']

In production on the other hand I was thinking about using config variable like:

#config/settings.yml
privileged_users: ENV["PRIVILEGED_USERS"]

My question is if I can set multiple values to that variable in an array? I'm deploying my app to Heroku.

Upvotes: 2

Views: 2050

Answers (3)

Thomas
Thomas

Reputation: 622

The original question was if an env variable could be an array. The answer is no, not an Heroku anyway, as https://github.com/railsconfig/rails_config states concerning arrays in section heroku: "It won't work with arrays, though.". We ended up with storing multiple values as a string and splitting them. Thx Rene!

ENV['PRIVILEGED_USERS'] = "[email protected], [email protected]"

def is_privileged?
 Settings.privileged_users.split(',').include?(email)
end

Upvotes: 1

Armando Fox
Armando Fox

Reputation: 309

In general, settings files should really be used for truly static or configuration data. Are you sure you don't want to have a privileged flag on your User model and just store this info in the database? Then you wouldn't have to redeploy the code just to change who is on that list:

class AddPrivilegedFlagToUsers < ActiveRecord::Migration
  def up ; add_column :users, :privileged, :boolean, :default => false ; end
  def down ; remove_column :users, :privileged
end

and then your check is simply:

if current_user.privileged?  
  # do stuff
end

Upvotes: 2

Zero Fiber
Zero Fiber

Reputation: 4465

You can pass in an array as a string and YAML should parse it correctly.

So your settings will remain the same and your env variable will be:

PRIVILEGED_USERS="['[email protected]', '[email protected]']"

Upvotes: 2

Related Questions