[英]Multilevel block methods in rails
我正在做一個視圖助手以一種格式呈現數據集。 我上這些課
require 'app/data_list/helper'
module App
module DataList
autoload :Builder, 'app/data_list/builder'
@@data_list_tag = :ol
@@list_tag = :ul
end
end
ActionView::Base.send :include, App::DataList::Helper
助手是
module App
module DataList
module Helper
def data_list_for(object, html_options={}, &block)
builder = App::DataList::Builder
arr_content = []
object.each do |o|
arr_content << capture(builder.new(o, self), &block)
end
content_tag(:ol, arr_content.join(" ").html_safe, html_options).html_safe
end
end
end
end
建造者是
require 'app/data_list/column'
module App
module DataList
class Builder
include App::DataList::Column
include ActionView::Helpers::TagHelper
include ActionView::Helpers::AssetTagHelper
attr_reader :object, :template
def initialize(object, template)
@object, @template = object, template
end
protected
def wrap_list_item(name, value, options, &block)
content_tag(:li, value).html_safe
end
end
end
end
列模塊為
module App
module DataList
module Column
def column(attribute_name, options={}, &block)
collection_block, block = block, nil if block_given?
puts attribute_name
value = if block
block
elsif @object.respond_to?(:"human_#{attribute_name}")
@object.send :"human_#{attribute_name}"
else
@object.send(attribute_name)
end
wrap_list_item(attribute_name, value, options, &collection_block)
end
end
end
end
現在我編寫代碼進行測試
<%= data_list_for @contracts do |l| %>
<%= l.column :age %>
<%= l.column :contact do |c| %>
<%= c.column :phones %>
<% end %>
<%= l.column :company %>
<% end %>
一切都很好, age
, contact
, company
都很好。 但是沒有顯示contact
phones
。
有沒有人有一個主意,我知道我錯過了代碼中的某些內容。 尋找您的幫助。
具有完整源代碼的更新問題是在此處輸入鏈接描述
我可以在列模塊中看到兩個問題。
1)如果提供了塊,則將其設置為nil-因此, if block
始終返回false。 2)即使block
不是nil,您也只是將block作為值返回,而實際上沒有將控制權傳遞給block。 您應該調用block.call
或block.call
。 隱式塊的執行速度更快,因此我認為您的列模塊應更像這樣:
module DataList
module Column
def column(attribute_name, options={})
value = begin
if block_given?
yield self.class.new(@object.send(attribute_name), @template)
elsif @object.respond_to?(:"human_#{attribute_name}")
@object.send :"human_#{attribute_name}"
else
@object.send(attribute_name)
end
end
wrap_list_item(attribute_name, value, options)
end
end
end
解決方案現已發布在討論中 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.