使用& block将html传递给方法

时间:2016-09-07 06:51:09

标签: ruby-on-rails ruby

如何将块传递给方法。例如:

# in the view
button(link) do
  '<div>html content</div>'
end

def button(&block)
  block
end

我有以下代码正在运行:

# in helper file
def button(&block)
  link_to '/' do
      block.call.html_safe
  end
end


# in the view
button {'<div>html content</div>'}

3 个答案:

答案 0 :(得分:3)

那么,您只想将块传递给link_to?这样做。

def button(&block)
  link_to '/', &block
end

答案 1 :(得分:2)

你可能搞砸了。你想要实现的目标是很容易实现的,没有任何yield魔法,使用普通的旧方法参数:

def button html
  link_to '/', html.html_safe
end

button '<div>html content</div>'

如果想要从块中获取值,请对其执行某些操作并将其进一步传递,可能会:

def button
  raise unless block_given?
  λ = Proc.new
  link_to '/', &-> { λ.call.html_safe }
end

button { '<div>html content</div>' }

答案 2 :(得分:1)

使用yield:

var SiteUrl1 = "http://yourwebsite"
var SPUsername1 = "domainName\userName";
var password = "pass";
var securePassword = new SecureString();
foreach (char c in password)
{
   securePassword.AppendChar(c);
}
ClientContext context = new ClientContext(SiteUrl1);
var credentials = new NetworkCredential(SPUsername1, password);
context.Credentials = credentials;