[英]ruby on rails passing block instead of argument
我有一个Rails 4应用程序。 为了识别链接,我使用了rinku
gem。 现在,我正在尝试集成best_in_place
gem进行内联编辑。 在我的post_comment.body
属性上,我想同时使用两者,但无法弄清楚如何使它们协同工作。
仅具有rinku
原始代码:
<%= find_links(h post_comment.body) %>
#And the corresponding method:
def find_links(text)
found_link = Rinku.auto_link(text, mode=:all, 'target="_blank"', skip_tags=nil).html_safe
end
仅使用best_in_place
会看起来像这样:
<%= best_in_place post_comment, :body, as: :input, url: post_post_comment_path(post_comment.post, post_comment), activator: "#activate-comment-edit-#{post_comment.id}" %>
现在,我尝试合并的方式,但是出现了错误的args错误数:
<%= find_links do %>
<%= best_in_place post_comment, :body, as: :input, url: post_post_comment_path(post_comment.post, post_comment), activator: "#activate-comment-edit-#{post_comment.id}" %>
<% end %>
我该如何进行这项工作? 在这种情况下,ruby / rails约定是什么? 我想我应该以某种方式通过,但我不知道该怎么做。
有多种方法可以完成此操作,具体取决于您要实现的目标。 这是一种方式。
def find_links(text = nil)
if block_given?
text ||= yield
end
raise ArgumentError, 'missing text' unless text
found_link = Rinku.auto_link(text, mode=:all, 'target="_blank"', skip_tags=nil).html_safe
或者,您可以让您的方法显式捕获该块:
def find_links(text = nil, &block)
text ||= block.call if block
raise ArgumentError, 'missing text' unless text
found_link = Rinku.auto_link(text, mode=:all, 'target="_blank"', skip_tags=nil).html_safe
需要澄清的是,您实际上不能“将块传递给方法”。 每次使用块时,它都会被传递给方法。 您的方法需要显式yield
该块,或者需要将其捕获到Proc
。 区别在于, Proc
绑定了评估上下文。
而且要完整:您可以将Proc
传递到您的方法中(就像您将其他任何变量一样),但是像上面这样使用yield
更加习惯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.