Created
May 23, 2013 09:18
-
-
Save joho/5633901 to your computer and use it in GitHub Desktop.
How I do Django-esque formsin Rails
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
# Borrowing the idea for this from http://pivotallabs.com/users/jdean/blog/articles/1706-form-backing-objects-for-fun-and-profit | |
class Forms::Base | |
# ActiveModel plumbing to make `form_for` work | |
extend ActiveModel::Naming | |
include ActiveModel::Conversion | |
include ActiveModel::Validations | |
def persisted? | |
false | |
end | |
end | |
# A specific form model | |
class Forms::UserProfile < Forms::Base | |
def initialize(user) | |
@user = user | |
end | |
attr_reader :user | |
delegate :username, :username=, to: :user | |
delegate :dont_index_me_bro, :dont_index_me_bro?, :dont_index_me_bro=, to: :user | |
delegate :errors, to: user | |
attr_accessor :profile_image_source | |
def full_name | |
user.full_name || user.first_name | |
end | |
def full_name=(new_name) | |
user.full_name = new_name | |
user.first_name = new_name.split(' ')[0] | |
end | |
def save | |
user.save | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment