At times, we need to set class constants in Ruby, something like:
class Foo
BAR = Rails.application.secrets.BAZ['BAR']
end
This gets messy at times when we want to declare a lot of constants, by reading the same variable name from secrets.yml
or env
.
After a bit of research, I came across a helpful utility provided by ruby, const_set
.
We can use it like:
module A
# To fasciliate in time submission of karvy orders
class B
%w[E F G H].each do |cred|
const_set(cred, Rails.application.secrets.['X'][cred])
end
end
end
A similar utility is const_get
, which is quite self explanatory for what it does.