Skip to content

Instantly share code, notes, and snippets.

@roidrage
Created December 6, 2012 11:07
Show Gist options
  • Save roidrage/4223741 to your computer and use it in GitHub Desktop.
Save roidrage/4223741 to your computer and use it in GitHub Desktop.
class Form
include ActiveModel::Validations
extend ActiveModel::Naming
def self.wraps(model)
@wraps = model
end
def self.model_name
ActiveModel::Name.new(@wraps.to_s.classify.constantize)
end
def initialize(model, attributes = {})
@model = model
attributes.each do |name, value|
send("#{name}=", value)
end
end
def to_key
@model.to_key
end
def attributes
Hash.new.tap do |atts|
instance_variables.each do |ivar|
next if [:@errors, :@model].include?(ivar)
att = ivar[1..-1].to_sym
atts[att] = send(att)
end
end
end
end
class EditPersonForm < Form
wraps :person
attr_accessor :first_name, :last_name
validates_presence_of :first_name, :last_name
end
def update
@form = EditPersonForm.new(person, params[:person])
if @form.valid?
person.update_attributes(@form.attributes)
else
render :edit
end
end
def person
Person.find(params[:id])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment