2
\$\begingroup\$

I'm starting Rails and Ruby for a short time. But I try to make it the cleanest way I can. So, in an attempt to clean my view, I try to custom my FormBuilder:

# /config/initializers/custom_form_builder.rb    
class ActionView::Helpers::FormBuilder

  # My test form function
  def test label
    return "Whatever I want to do ..."
  end
end

And then I can use it like this:

# /app/views/test/test.html.erb
...
<%= form_for test, :html => {:multipart => true} do |f| %>
  ...
  <%= f.test(":-)") %>
  ...
<% end %>
...

This part works perfectly fine. However, what I want to do know is how to create form views containing the HTML code that I want to use in my forms. This way, I can store the HTML of all my form in a pseudo-HTML way, and structured within my directories.

So, I've created a template:

# /app/views/forms/test.html.erb
<input type="text" value="test" />

And I've tried to render it from my FormBuilder:

# /config/initializers/custom_form_builder.rb
def test label
  render "forms/test"
end

And I added it to my routes:

# /config/routes.rb
match "/forms/test"    => "forms#test"

My questions:

  1. Do I try to make it work the wrong way?
  2. Is it possible to render from my FormBuilder class?
  3. Is there some useless code in there?
\$\endgroup\$
1
\$\begingroup\$

I made it a different way. But, the answer was quite simple.

The class ActionView::Helpers::FormBuilder inherit of the @template attribute.

And to render my partials, I just need to call it this way :

def test label
  @template.render "/forms/test"
end

Then you can use the partial as specified on RoR Guides

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.