加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails的concat方法和带有do … end的块不起作

发布时间:2020-12-17 03:16:50 所属栏目:百科 来源:网络整理
导读:我刚刚阅读了Rails的concat方法来清理在 http://thepugautomatic.com/2013/06/helpers/输出内容的帮助程序. 我玩弄了它,我发现它对于带有花括号的块和带有do … end的块没有同样的反应. def output_something concat content_tag :strong { "hello" } # work
我刚刚阅读了Rails的concat方法来清理在 http://thepugautomatic.com/2013/06/helpers/输出内容的帮助程序.

我玩弄了它,我发现它对于带有花括号的块和带有do … end的块没有同样的反应.

def output_something
  concat content_tag :strong { "hello" } # works
  concat content_tag :strong do "hello" end # doesn't work
  concat(content_tag :strong do "hello" end) # works,but doesn't make much sense to use with multi line blocks
end

我不知道花括号和做…结束块似乎有不同的含义.有没有办法使用concat with do … end而不用括号括起来(第3个例子)?否则在某些情况下似乎没用,例如当我想在UL中连接许多LI元素时,我必须使用多行代码.

解决方法

归结为Ruby的范围.使用concat content_tag:strong执行“hello”结束时,块将传递给concat,而不是content_tag.

使用此代码玩具,你会看到:

def concat(x)
  puts "concat #{x}"
  puts "concat got block!" if block_given?
end

def content_tag(name)
  puts "content_tag #{name}"
  puts "content_tag got block!" if block_given?
  "return value of content_tag"
end

concat content_tag :strong do end
concat content_tag :strong {}

引用:Henrik N来自“使用concat和capture来清理自定义Rails助手”(http://thepugautomatic.com/2013/06/helpers/)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读