Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save scottbaggett/4305760 to your computer and use it in GitHub Desktop.
Save scottbaggett/4305760 to your computer and use it in GitHub Desktop.
# db/migrations/20120118012543_create_site_configuration.rb
class CreateSiteConfigurations < ActiveRecord::Migration
def change
create_table :site_configurations do |t|
t.string :key
t.text :value
t.string :form_type
t.string :form_collection_command
t.timestamps
end
add_index :site_configurations, :key, unique: true
end
end
// app/views/admin/settings/index.html.haml
= semantic_form_for :update_site_configuration, :url => admin_site_configuration_path(0), :method => :put do |form|
= form.inputs do
- SiteConfiguration.all.each do |record|
= form.input record.key.to_sym, as: record.form_type.to_sym, input_html: {value: record.value}, :include_blank => false, collection: (options_from_collection_for_select(eval(record.form_collection_command), 'id', 'to_s', record.value) if record.form_collection_command.present?)
= form.buttons do
= form.submit "Update Site Configuration"
# app/models/site_configuration.rb
class SiteConfiguration < ActiveRecord::Base
serialize :value
class_attribute :settings
self.settings = []
def self.ensure_created
self.settings.each do |setting|
self.send(setting)
end
end
def self.setting(name, default, form_type, form_collection_command="")
class_eval <<-EOC
self.settings << "#{name}"
def self.#{name}
@#{name} ||= self.find_or_create_by_key("#{name}", value: #{default}, form_type: "#{form_type}", form_collection_command: "#{form_collection_command}").value
end
def self.#{name}=(value)
record = self.find_or_create_by_key("#{name}", value: #{default}, form_type: "#{form_type}", form_collection_command: "#{form_collection_command}")
record.value = value
record.save!
@#{name} = value
end
EOC
end
# Define settings by listing them here
setting :contact_page_id, 2, :select, "Page.all"
setting :top_menu_id, 1, :select, "Menu.all"
setting :customer_service_menu_id, 2, :select, "Menu.all"
setting :footer_menu_id, 3, :select, "Menu.all"
setting :notification_addresses, "'admin@example.com'", :string
# Ensure all the defaults are created when the class file is read
self.ensure_created
end
# app/admin/site_configurations.rb
ActiveAdmin.register SiteConfiguration do
actions :only => [:index, :update]
before_filter do
@skip_sidebar = true
end
config.comments = false
config.clear_action_items!
controller do
def index
params[:action] = "Site Configuration" # for the active admin title
render 'admin/settings/index', :layout => 'active_admin'
end
def update
params[:update_site_configuration].each do |setting, value|
SiteConfiguration.send("#{setting}=", value)
end
redirect_to :back, notice: "Settings Saved"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment