Created
December 6, 2012 11:07
-
-
Save roidrage/4223741 to your computer and use it in GitHub Desktop.
This file contains 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
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 |
This file contains 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
class EditPersonForm < Form | |
wraps :person | |
attr_accessor :first_name, :last_name | |
validates_presence_of :first_name, :last_name | |
end |
This file contains 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
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