daniel
daniel

Reputation: 9845

DRY me. Rails code:

I have several of this, where the only thing that differs is if its a text_field or a password_field etc etc etc. I'd like to pass this as a parameter to the render, like :as => :password_field for example. And I don't wan't to do a case compare, the value passed in the :as is the value of the field. Is this possible ?


.text{:class => form.object.errors[field].any? ? "error" : nil}
  = form.label field
  -if defined? value
    = form.text_field field, :value => value
  -else
    = form.password_field field 
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field           

.text{:class => form.object.errors[field].any? ? "error" : nil}
  = form.label field
  -if defined? value
    = form.text_area field, :value => value
  -else
    = form.text_area field 
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field 

Answer is the one below, with some fixes:


-# expects form, field_name, field_type, value and hint variables to be passed
.text{:class => form.object.errors[field_name].any? ? "error" : nil}
  = form.label field_name
  - if defined?(value)
    = form.send(field_type, field_name, :value => value)
  - else
    /= form.send(:field_type, field_name)   
    = form.send(field_type, field_name)   
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field_name        

Usage: = render 'shared/form_field', :form => f, :field_name => :email, :field_type => :text_field

Upvotes: 0

Views: 351

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64373

Create a partial called shared/form_field.html.haml

- # expects form, field_name, field_type, value and hint variables to be passed
.text{:class => form.object.errors[field_name].any? ? "error" : nil}
  = form.label field_name
  - if defined?(value)
    = form.send(:field_type, field_name, :value => value)
  - else
    = form.send(:field_type, field_name)
  -if defined? hint
    %p#hint= hint
  = render 'shared/error_messages', :object => form.object, :field => field_name 

You can invoke the partial as

- form_for :user do |form|
 = render 'shared/form_field', :locals => {:form => form, 
                        :field_name => :login, :field_type => :text_field}

Upvotes: 1

nfm
nfm

Reputation: 20747

If I understand your question right, you're after this:

render :partial => 'user/login_errors', :locals => { :field => :first_name, :value => @user.first_name, :form => form }

You use the locals hash to pass in any number of variables. In your case, the variables in your code snippet were form, field, and value. The keys in the hash determine what the variable will be referenced as in the partial, and the values in the hash determine the variable values.

Upvotes: 1

Related Questions