Skip to content

Instantly share code, notes, and snippets.

@lcguida
Last active March 18, 2016 19:24
Show Gist options
  • Save lcguida/c7b32f7d9e5073d934ba to your computer and use it in GitHub Desktop.
Save lcguida/c7b32f7d9e5073d934ba to your computer and use it in GitHub Desktop.
Dynamic Loading Settings
class AppConfig < ActiveRecord::Base
validates :parameter, uniqueness: true, presence: true
def self.get(parameter)
AppConfig.where(parameter: parameter).first.try(:value)
end
def self.set(parameter, value)
param = AppConfig.find_or_initialize_by(parameter: parameter)
param.value = value
param.save
end
end
class AppConfigsController < ApplicationController
def edit
authorize :settings
configs = AppConfig.all
@settings = Settings.new(configs)
end
def update
authorize :settings
settings_params.each do |parameter, value|
AppConfig.transaction do
begin
config = AppConfig.set(parameter, value)
end
end
end
flash[:notice] = "Configurations successfuly updated"
redirect_to edit_settings_path
end
private
def settings_params
#Novas configurações devem ser permitidas aqui
params.require(:settings).permit(:language)
end
end
<!-- Here You just need to worry about creating the fields that exists in the database -->
<%= simple_form_for @settings, url: save_settings_path do |f| %>
<%= f.input :language, required: true, collection: Settings.language_options,
selected: I18n.locale %>
<%= f.button :submit, class: "btn-success" %>
<% end %>
get '/settings' => "app_configs#edit", as: :edit_settings
put '/settings' => "app_configs#update", as: :save_settings
patch '/settings' => "app_configs#update"
class Settings
include ActiveModel::Model
extend ActiveModel::Naming # Necessary for trasnlations
# The constructor reveices an array of AppConfig containing all the configs
# and then he translate it to settings porperties
def initialize(app_configs)
app_configs.each do |config|
# Creates an attribute acessor (get and set) for the paremeter
self.class.send(:attr_accessor, config.parameter)
# Creates an instance varibale for the paremeter, passing the value
instance_variable_set("@#{config.parameter}", config.value)
end
end
def app_configs
configs = []
instance_variables.each do |variable|
parameter = variable.to_s.sub!(/[^0-9A-Za-z]/, '') #Removes the '@'
value = send(parameter) # Get the value of the parameter
configs << { parameter: parameter, value: value }
end
configs
end
def self.language_options
locales = []
I18n.available_locales.each do |locale|
locales << [I18n.t(locale, scope: :locales), locale]
end
locales
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment