Last active
August 29, 2015 14:19
-
-
Save Slike9/345d6592de64cf898663 to your computer and use it in GitHub Desktop.
rails_model_form_v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ModelForm | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :model_class | |
self.model_class = self.superclass | |
class_attribute :permitted_attrs | |
self.permitted_attrs = [] | |
end | |
module ClassMethods | |
def model_name | |
model_class.model_name | |
end | |
def permit(*permitted_attrs) | |
self.permitted_attrs.concat permitted_attrs | |
end | |
def wrap(model) | |
model.becomes(self).tap do |form| | |
form.send :set_model, model | |
end | |
end | |
def form_field(name, options={}) | |
if options[:accessor] | |
attr_accessor name | |
end | |
permit name | |
end | |
def form_fields(*names, **options) | |
names.each do |name| | |
form_field(name, options) | |
end | |
end | |
end | |
def assign_attributes(attrs = {}) | |
if attrs.respond_to?(:permitted?) | |
attrs = attrs.permit(*permitted_attrs) | |
end | |
super(attrs) | |
end | |
def model | |
@model ||= self.becomes(self.class.model_class) | |
end | |
private | |
def set_model(model) | |
@model = model | |
if respond_to?(:load_model, true) | |
send(:load_model, model) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment