Skip to content

Instantly share code, notes, and snippets.

@eriko
Last active July 10, 2018 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eriko/d21f676ad239fd432fed to your computer and use it in GitHub Desktop.
Save eriko/d21f676ad239fd432fed to your computer and use it in GitHub Desktop.
<%= semantic_form_for @project, :remote => true, :validate => true, :class => "form-horizontal" do |f| %>
<%= f.semantic_fields_for :settings do |sets| %>
<%= sets.semantic_fields_for :colors , @project.sets.fileshare do |colors| %>
<%= colors.input :border,
:label => "Edge color of all project objects",
:default => false,
:as => :radio,
:input_html => {:disabled => @project.created}
%>
<%= colors.input :fill,
:label => "Fill colors for all project objects",
:default => false,
:as => :radio,
:input_html => {:disabled => @project.created}
%>
<% end %>
<% end %>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<%= f.button :submit, :class => 'btn btn-primary' %>
</div>
<% end %>
This is a crappy example of how to use https://github.com/ledermann/rails-settings in a form. The setting get turned into a hierarchy of SetttingsObjects and then are used to set the form values. The settings will come back as "project"=>{ "settings"=>{"colors"=>{"edge"=>"red", "fill"=>"blue"}}} from the form and are proccessed in the controller code. strong_parameters is completely ignored. This is probably a bad thing that could be fix
class Project < ActiveRecord::Base
...
def sets
SettingsObject.new(self.to_settings_hash)
end
...
end
def create
@project = Project.new(project_params)
if params[:project][:settings] &&params[:project][:settings][:colors]
params[:project][:settings][:color].each do |key, value|
@project.settings(:colors).send("#{key}=", value)
end
....
end
or
def create
@project = Project.new(project_params)
import_settings(@project, params)
....
end
private
def import_settings(klass, params)
class_for_settings = params[:controller].singularize.to_sym
if params[class_for_settings][:settings]
params[class_for_settings][:settings].keys.each do |namespace|
params[class_for_settings][:settings][namespace].each do |key, value|
klass.settings(namespace.to_sym).send("#{key}=", value)
end
end
end
klass
end
class SettingsObject < Object
attr_accessor :hash
def initialize(hash)
@hash = Hash.new
hash.each do |key, value|
unless value.is_a?(Hash)
@hash[key.to_sym] = value
else
@hash[key.to_sym] = SettingsObject.new(value)
end
end
end
def method_missing(method_name, *args, &block)
if @hash.has_key? method_name.to_sym
@hash[method_name.to_sym]
else
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment