📜 ⬆️ ⬇️

Custom configuration file in Rails

image

I just recently got acquainted with the world of Rails, and how every first-grader has a dozen questions, most with which an experienced developer can make you smile. Having written the first three projects, I had a banal question about storing additional configuration data in a file. That is, when we start we read the data from the user configuration file, during the work of the app we can change something if necessary and carefully save everything to the same file.

As a result of studying this issue, I was looking for a gem, the functionality of which performs this mission, but did not find it. Most likely I’m doing something wrong, because in the gem’s documentation, I don’t see how to save the data to a file (I think the problem is in my misunderstanding)

And so, my implementation:
')


First we edit the config / application.rb

require 'yaml' if File.exist? Rails.root.join('config', 'settings.yml') config.settings = YAML::load_file(Rails.root.join('config', 'settings.yml')) else config.settings = {} end 


Controller settings_controller.rb
 class Admin::SettingsController < AdminController def index @settings=Rails.application.config.settings end def create flash[:success] = "  " File.open("settings.yml", "w") do |file| file.write settings_params.to_yaml end Rails.application.config.settings=settings_params redirect_to admin_settings_index_path end private def settings_params params.permit(:name, :email) end end 


Well, actually view
 <% provide(:title, '') %> <%= bootstrap_form_tag @settings do |f| %> <%= f.text_field :name, label: "", value: f.options[:name] %> <%= f.text_field :email, label: "e-mail", value: f.options[:email] %> <%= f.submit "  ", class: "btn btn-success" %> <%= link_to "  ", admin_root_path, class: "btn btn-danger" %> <% end %> 

Source: https://habr.com/ru/post/278801/


All Articles