Skip to content

Instantly share code, notes, and snippets.

@qwzybug
Created April 16, 2009 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qwzybug/96698 to your computer and use it in GitHub Desktop.
Save qwzybug/96698 to your computer and use it in GitHub Desktop.
## 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