Skip to content

Instantly share code, notes, and snippets.

@hansjag04
Last active May 31, 2017 11:57
Show Gist options
  • Select an option

  • Save hansjag04/4fbf70915682735557785269a237b51e to your computer and use it in GitHub Desktop.

Select an option

Save hansjag04/4fbf70915682735557785269a237b51e to your computer and use it in GitHub Desktop.
Rails Settings Cached Edit view with Mongoid and mongoid app settings gem
App Settings Edit Form in Rails 5 using Mongoid
* With mongoid-app_settings gem (https://github.com/marten/mongoid-app_settings)
* Inspired on 'rails-settings' gem for ActiveRecord
Made this gist because couldn't find any code/post to update this gem (or hashed arrays) with a view form on Rails.
Based on the ZedTuX answer (Option 2) on this SO question
(https://stackoverflow.com/questions/16690193/how-to-edit-rails-serialized-hashes-in-a-form)
- Hans Araya
- Computer Engineering, Costa Rica Institute of Technology (TEC)
#Using mongoid-app_settings gem (https://github.com/marten/mongoid-app_settings)
gem 'mongoid-app_settings'
#Your Index view for Settings
/ (...)
= form_for @setting, method: :put do |f|
= f.label :my_feature #Using fake atrribute
= f.number_field :my_feature, step: :any, :required => true # Because this feature is an Integer
/ submit button
/ (...)
class MySetting
include Mongoid::Document
include Mongoid::AppSettings
field :my_feature, type: Integer, default: 0 #Fake attribute just to use with form_for on views
setting :my_feature_setting, type: Integer, default: 0 #Real setting. Using '_setting' to know what the real setting is
def my_feature
MySetting.my_feature_setting
end
def my_feature=(value)
MySetting.my_feature_setting = value
end
end
#I just need index with GET
resources :settings, only: [:index]
#Match the PUT with Update method (default mode would be '/settings/:id' but I don't need any 'id'
match '/settings' => 'settings#update', via: [:put]
#I'm using the Index as the Edit Form to load all settings
class SettingsController < ApplicationController
def index
MySetting.reload #Refresh all cached settings
@setting = MySetting.new #fake "new" MySetting object
end
def update
respond_to do |format|
if MySetting.new(settings_params) #Fake "new" (without saving) just to update static values
flash[:notice] = "Your settings have been updated successfully."
format.html { redirect_to index}
format.json { render :show, status: :ok}
else
format.html { redirect_to index }
format.json { render json: @ajuste.errors, status: :unprocessable_entity }
end
end
end
def settings_params
params.require(:setting).permit(:my_feature) #and all the features you need
end
end
def your_method
your_var = get_feature
puts your_var # :D
end
def get_feature
MySetting.reload
MySetting.my_feature_setting
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment