Tutorial: Storing Business dependant environmental variables on the database layer [Ruby on Rails]

Create a new model called “Config”

rails g model config

Setup the table like so

def change
create_table :configs do |t|
t.string :key
t.text :value
t.string :convert_by
t.timestamps
end
add_index :configs, :key, unique: true
end

key

Defines the key that you’ll use for the environmental variable eg. shopify_api_secret

value

Is the psychical value of the environmental variable

convert_by

Is the conversion helper, so you can use the value as intended and write less code. Examples include to_d and to_s

Migrate

rake db:migrate

Define a set function

This function will set variables by the value that you give them. Config.set(:token, "1234abcd", "to_s")

class Config < ApplicationRecord  def self.set sym, value, convert_by
record = find_or_initialize_by(key: sym.to_s)
record.value = value
record.convert_by = convert_by
record.save
response = record ? record.convert : nil
end
end

Define a use and convert function

This function will be accessed the most. It pulls the variable from the database converts it to the correct type and them returns the value (or nil)

class Config < ApplicationRecord  def self.use sym
record = find_by(key: sym.to_s)
response = record ? record.convert : nil
end
def convert
return self.value == "t" if self.convert_by == "to_b"
return self.value.send(self.convert_by.to_sym)
end
def self.set sym, value, convert_by
...
end
end

Set and use a defined ENV variable

Config.set(:max_distance_for_free_shipping, "5.7", "to_d")Config.use(:max_distance_for_free_shipping) => 5.7
if Config.use(:max_distance_for_free_shipping) > customer.distance_from_shop  return {
error: "we don't service your area",
result: false
}
else
return {
error: nil,
result: true
}
end

Encryption

If you are storing sensitive data that shouldn’t be viewed by anyone but the application, you should look at encrypting it. I won’t go into that too much here but Pawel Urbanek has written a good piece on storing encrypted data on the database layer.

Conclusion

Not all Env variables are the same or equal. Some require more frequent access and should be treated differently in how they are stored and deployed.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store