[英]Loop through block in rails helper
I'm trying to create a Rails helper that takes a block and loops through that to produce: 我正在尝试创建一个Rails助手,该助手需要一个块并循环遍历以产生:
<span data-param1="param1" data-param2="param2">
<span data-options="test">
<span data-options="test">
</span>
An example of the helper in use: 使用中的助手的示例:
<%= main(param1, param2) do %>
<%= sub('param', :options => 'test') %>
<%= sub('param', 'test') %>
<% end %>
And then the helper itself: 然后助手本身:
module MyHelper
def main(param1, param2, &block)
raise ArgumentError.new('Missing block!') unless block_given?
content_tag :span, :data => { :param1 => param1, :picture => '' } do
markup = content_tag(:span, '', :data => { :param2 => param2 }).to_s
#loop through blocks of subs
&block.each do |item|
sub = sub(item.param, item.options)
data = { :param => param }
data[:options] = sub.options unless sub.options.blank?
markup << content_tag(:span, '', :data => data).to_s
end
markup
end
private
def sub(param, options = {})
options = extract_options!(options)
end
# returns a string
def extract_options!(options)
when String
options
when Hash
#removed for this question
else
raise ArgumentError.new('Only Hash && String allowed!')
end
end
Note: I've removed the Hash
handling in the extract_options to keep the question code short. 注意:为了使问题代码简短,我已经删除了extract_options中的Hash
处理。
However it doesn't like the &block
loop and gives this error: 但是,它不喜欢&block
循环并给出以下错误:
syntax error, unexpected &, expecting keyword_end
&block.each do |item|
^
First of all, block basically is a Proc
instance and Proc
does not by any mean implements Enumerable
, hence calling each
on it won't succeed in any case. 首先,block基本上是一个Proc
实例,而Proc
绝不实现Enumerable
,因此在任何情况下对其调用each
都不会成功。
I wonder, what's wrong with passing an array to main
? 我想知道,将数组传递给main
什么问题? What are you trying to achieve? 您想达到什么目的?
The code example that works: 有效的代码示例:
def main(param1, param2, *subs)
...
subs.each ...
end
<%= main(param1, param2, sub('param', :options => 'test'), sub('param', 'test')) %>
Whether you still want to use a block
(why?): 是否仍要使用block
(为什么?):
def main(param1, param2, &block)
...
yield.each ...
end
<%= main param1, param2 do %>
<%= [sub('param', :options => 'test'), sub('param', 'test')] %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.