Created
April 16, 2009 21:49
-
-
Save qwzybug/96698 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
## Implementation | |
class FormBuilder | |
def initialize obj, ctx | |
@obj, @ctx = obj, ctx | |
end | |
def method_missing m, *args | |
@ctx.send(m, @obj, *args) | |
end | |
end | |
def form_for obj, action, &block | |
haml_tag 'form', :method => 'POST', :action => action do | |
haml_tag('dl') { block.call FormBuilder.new(obj, self) } | |
end | |
end | |
def field_for obj, property, opts = {} | |
opts = {:name => "#{obj.class.name.downcase}[#{property}]", :value => "#{obj.send(property)}"}.merge opts | |
haml_tag 'dt', property.to_s.humanize | |
haml_tag 'dd', :class => (obj.errors[property] ? 'error' : nil) do | |
haml_tag 'input', opts | |
haml_tag 'div', obj.errors[property].join("; "), :class => 'error' if obj.errors[property] | |
end | |
end | |
## Usage | |
- form_for @new_user, '/users/create' do |f| | |
= f.field_for :name, :size => 30 | |
= f.field_for :email, :size => 30 | |
= f.field_for :password, :type => 'password', :size => 15 | |
= f.field_for :password_confirmation, :type => 'password', :size => 15 | |
%button Create User |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment