block methods in ruby



我正在使用块方法打印列表,但是它正在生成错误。

  class MyDataListBuilder
    attr_accessor :object
    def initialize(object)
      @object = object
    end
    def column (&block)
      content_tag :li, block.call
    end
  end

并将其用作

<%= my_data_list_for @leads, [" :10", "Age:30", "Contact:140", "Phone:140", "Email:180", "Company:100", ""] do |l| %>
        <%= l.column do %>
            <%= object.age %>
        <% end %>
    <% end %>

其他方法

def list_headers(args=[])
    args    = Array.new(args)
    columns = []
    args.map { |o| columns << content_tag(:li, o.split(":").first, :style=>"width:#{o.split(":").second}px;") }
    content_tag(:ul, columns.join(" ").html_safe, :class=>"list-headers")
  end
  def my_data_list_for(object, headers=[], &block)
    arr = []
    object.each do |o|
      arr = capture(DataListHelper::MyDataListBuilder.new(o), &block)
    end
    content_tag(:ol, list_headers(headers) + arr, :class=>"data-list")
  end

它正在生成一个错误,我不知道为什么:

ActionView::Template::Error (undefined local variable or method `object' for #<#<Class:0xcaa1ca0>:0xca9ebf4>):

请帮帮我。

问题解决了。

class MyDataListBuilder
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::CaptureHelper
    attr_accessor :object, :output_buffer
    def initialize(object)
      @object        = object
      @output_buffer = nil
    end
    def column (&block)
      if block_given?
        content_tag(:li, capture(self, &block))
      else
        content_tag(:li, "")
      end
    end
  end

相关内容

  • 没有找到相关文章

最新更新