maček
maček

Reputation: 77826

View helper with Rails returns the wrong value [Rails, Ruby]

I am trying to write a view helper but it's not returning the correct thing.

def table_layout_for(object, *attrs)
  content_tag :table, :class => "layout" do
    for a in attrs
      content_tag :th do
        object.class.human_attribute_name(a)
      end
      content_tag :td do
        object.send(a) if object.respond_to?(a)
      end
    end
  end
end

This problem:

<%= table_layout_for(@user, :email, :full_name, :business_name, :phone_number) %>

Returns this:

[:email, :full_name, :business_name, :phone_number]

I'd like it to return this:

<table class="layout"> 
  <tr> 
    <th>Email</th> 
    <td>[email protected]</td> 
  </tr> 
  <tr> 
    <th>Full name</th> 
    <td>Paul Macek</td> 
  </tr> 
  <tr> 
    <th>Business name</th> 
    <td>2bynight</td> 
  </tr> 
  <tr> 
    <th>Phone number</th> 
    <td>555-423-1245</td> 
  </tr> 
</table>

Upvotes: 1

Views: 236

Answers (1)

shingara
shingara

Reputation: 46914

it's because the content return by your block in your content_tag is your array, not all content_tag.

You need made :

def table_layout_for(object, *attrs)
  content_tag :table, :class => "layout" do
    ret = ''
    for a in attrs
      ret += content_tag :th do
        object.class.human_attribute_name(a)
      end
      ret += content_tag :td do
        object.send(a) if object.respond_to?(a)
      end
    end
    ret
  end
end

Upvotes: 1

Related Questions