Skip to content

Instantly share code, notes, and snippets.

@jbourassa
Created March 3, 2013 20:01
Show Gist options
  • Save jbourassa/5078018 to your computer and use it in GitHub Desktop.
Save jbourassa/5078018 to your computer and use it in GitHub Desktop.
Implementing `#method_missing` is an easy way to build funky forms with ActiveModel while keeping the magic.
<%= simple_form_for(@permissions) do |form| %>
<% @tags.each do |tag| %>
<h3><%= raw t('admin.permissions.tags', tag: tag.name) %></h3>
<%= form.input "tags[#{tag.key}]",
as: :check_boxes,
collection: tag.edit_select_opts,
label_method: :name,
value_method: :key,
label: false %>
<% end %>
<% end %>
class Permissions
include Mongoid::Document
field :tags, type: Hash, default: {}
# Defines `tags[__key__]=` and `tags[__key__]` for ActiveModel
# form and assign magic
def method_missing(method, *args, &block)
tag_key = extract_tag_from_method(method)
return super unless tags_with_access.include?(tag_key)
if method.to_s.match(/=$/)
tags[tag_key] = args.first
else
tags[tag_key]
end
end
def respond_to?(method, include_private=false)
tag_key = extract_tag_from_method(method)
if tag_key && tags_with_access.include?(tag_key)
true
else
super
end
end
private
def extract_tag_from_method(method)
match = method.to_s.match(/^tags\[(\w+)\]=?$/)
match ? match[1] : nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment