[英]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.