Anil Anil - 21 days ago 5
Ruby Question

How can I dynamically access all config parameters starting with 'var' defined in config/applications.rb?

In my config/applications.rb, I have set parameters:

config.var1 = 1
config.var2 = 5
config.varx = 7


I can access them using

Rails.application.config.var1


I am trying to dynamically build a hash of all config parameters with names starting with 'var', so the output would be

{var1: 1, var2: 5, varx: 7}


I have looked at the Rails.application.config.methods, Rails.application.config.instance_variables, Rails.application.config.inspect etc. and they don't return the var1 etc.

How can I dynamically access all config parameters starting with 'var' defined in config/applications.rb?

Thanks for your help.

Answer

While I completely agree with @SergioTulentsev that you are doing it wrong, you are still free to:

Rails::Railtie::Configuration.class_variable_get(:@@options)
                             .select { |k, _| k =~ /\Avar/ }
#⇒ {
#    :var1 => 42
# }

As a matter of fact, the access to this class variable is provided via method_missing.