alex
alex

Reputation: 521

ruby/rails block content problem

i wont to create simple tabs helper for dynamic tabs creation. Something like form_for rails helper.

Here what i have for now (simplified for example ):

class Tabs

    attr_reader :tabs, :type, :subtype, :args

    def initialize(*args)

      @tabs    = []
      @type    = args[0] || 'horizontal'
      @subtype = args[1] || 'basic'
      @args    = args.extract_options!
    end


    def tab(*args, &block)
      tab          ={}
      tab[:name]   =args[0]
      tab[:content]= capture(&block)
      #same thing with with_output_buffer(&block)
      args         = args.extract_options!
      tab          = args.merge(tab)
      @tabs << tab

    end


  end



  def tabs_navigation(*args, & block)
    tabs_constructor = Tabs.new(args)
    capture(tabs_constructor, & block)

    #iteration of tabs hash array and building tabs structure goes here
    #tabs_constructor.tabs.each bla,bla

end

in the view

 <%= tabs_navigation do |tabs| %>
        <% tabs.tab :tab1 do %>
            tab1
        <% end %>
        <% tabs.tab :tab2 do %>
            tab2
        <% end %>
         <% tabs.tab :tab3 do %>
            tab3
        <% end %>
    <% end %>

Everything works ok, except content for tabs is somehow joined like this:

content for tab1 is: :content=>"\n            tab1\n"
content for tab2 is: :content=>"\n            tab1\n            tab2\n"
content for tab3 is: :content=>"\n            tab1\n            tab2\n            tab3\n"

I'm new one and ruby blocks is something that i haven't to much experiences.

Can someone explain to me, what's going here and how to catch content of tab block?

Using ruby 1.9.2

Thanks

UPDATE

i try this from ruby:

class Foo
  attr_reader :arr
  def initialize
     @arr = []
  end

  def bar
    hash = {}
    hash[:content] = yield
    @arr << hash
  end
end

def FooBars
  foo = Foo.new
  yield foo
  puts foo.arr
end


FooBars do |fo|
  fo.bar do
    'bar1'
  end
  fo.bar do
    'bar2'
  end
end

end it works as expected. The problem/bug is in the rails view/erb blocks.. Can anybody help me with this?

thanks

Upvotes: 0

Views: 461

Answers (1)

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10772

If you look closely at your blocks you should see that all those characters being captured are there.

This can be approached in a few ways, here is one:

<%= tabs_navigation do |tabs| %>
    <% tabs.tab :tab1 do %>tab1<% end %>
    <% tabs.tab :tab2 do %>tab2<% end %>
    <% tabs.tab :tab3 do %>tab3<% end %>
<% end %>

I think this will only strip the first newline:

<%= tabs_navigation do |tabs| %>
    <% tabs.tab :tab1 do -%>
        tab1
    <% end %>
    <% tabs.tab :tab2 do -%>
        tab2
    <% end %>
    <% tabs.tab :tab3 do -%>
        tab3
    <% end %>
<% end %>

Personally, I'd probably just call strip() on the value returned by yield though

Upvotes: 1

Related Questions