Search code examples
rubyvariablesscoperequire

How to access a variable defined in secret.yml and required in other Ruby script


The secrets.yml file contains:

should_preferred_browser_driver: 0

In another script of the project called "rails_helper.rb", I want to access that variable.

  if should_preferred_browser_driver
    return Capybara.javascript_driver = :selenium_chrome
  else
    return Capybara.javascript_driver = :selenium_chrome_headless
  end

It displays an error:

Can not find 'should_preferred_browser_driver'

What is the way to access the variable which is defined in secrets.yml in rails_helper.rb?


Solution

  • Assuming you are using Rails, you should be able to access should_preferred_browser_driver variable by:

    Rails.application.secrets.should_preferred_browser_driver
    

    However, maybe a better approach is to handle with config within your ENV variables instead of the secrets. Figaro or dotenv gems are common in many projects.

    # config/application.yml -- Figaro example
      SHOULD_PREFERRED_BROWSER_DRIVER: 0
    
    # specs/rails_helper.rb
      if Integer(ENV.fetch("SHOULD_PREFERRED_BROWSER_DRIVER") { 0 }) 
        ...
      else
        ...
      end