DEV Community

loading...

How to use config / credentials file in rails.

vishal patidar
I am full stack developer. I know ReactJS , Ruby on Rails very well. And my aim is that i teach other people with my coding skills and knowledge.
・2 min read

In this post i am going to show to use config/credentials.yml.enc file in rails application. So let's get start all thing one by one. Before going forward we need to know what is the use of config/credentials.yml.enc file.

credential file is very important for every rails project with the help of this file we can store credential data like api key, password, username, emails etc in encrypted format.

So, what is the exactly need of credential file. For example you developed weather application and in this application you used weather API and after developed the application you pushed the code on GitHub (as a public repository) and that time anyone can see your personal weather API. So for that we use credential file with this anyone can't see you API key because of the file is in encrypt format.

So how to implement credential file in your rails project.

Firstly you have to create new rails application with rails new command. After doing this if you go to config/credentials.yml.enc file you will see that the file is encrypted format.

Next you have to add credential data like API key/password in the credentials.yml.enc file. So for that you have to run this given below command on the terminal.

$ cd weather_project

$ EDITOR="code --wait" rails credentials:edit  
Enter fullscreen mode Exit fullscreen mode

In the line i mentioned code keyword because i want to open this file on VSCode you can also open this file another IDE like Atom and when i run this command the credentials.yml.enc file open in Visual studio Code in decrypted format.like this

  # aws:
  #   access_key_id: 123
  #   secret_access_key: 345

  #  Used as the base secret for all MessageVerifiers in 
  Rails, including the one protecting cookies.
  secret_key_base:abcdefghijklmopadsaweqwe
Enter fullscreen mode Exit fullscreen mode

So now you have to uncomment top two line of code in this file. You can also add other API key and password like this.

  weather_api: 123456789
Enter fullscreen mode Exit fullscreen mode

After doing this save(ctrl+s) the file and close ❌ the VSCode. If you want to check that API key successfully add or not so for that run command on terminal.

  $ rails c

  $ Rails.application.credentials.weather_api
Enter fullscreen mode Exit fullscreen mode

Output - 123456789

Happy coding..😊

Discussion (0)