字符串连接和基于if修饰符的屈服块

时间:2016-06-22 19:44:57

标签: ruby

这是一个纯粹的ruby语法问题,即使它是在Rails的上下文中。

我有一个接受块的方法,并将其转换为定义中的proc对象:

def wrapper(form, attr, options = {}, &block)
  if block_given?
    yield(block) +
  end
  form.label(form_label, class: "control-label")
end

该块是一段html作为字符串,我想将它与form.label连接,它本身作为一个html字符串返回。但是,如果给出了块,我只想连接两个。

以上产生语法错误:

SyntaxError: (irb):14: syntax error, unexpected keyword_end

使用if修饰符也不起作用:

def wrapper(form, attr, options = {}, &block)
  yield(block) + if block_given?
  form.label(form_label, class: "control-label")
end

我可能以后也需要这样做(在这种情况下我会有条件地连接3个字符串):

def wrapper(form, attr, options = {}, &block)
  form.label(options[:errors], class: "control-label required") +
  yield(block) + if block_given?
  form.label(form_label, class: "control-label")
end

当块可以是可选的时,将块与字符串连接的最佳方法是什么?

在提出问题之后我想到的一个解决方案可能是:

   def wrapper(form, attr, options = {}, &block)     
     if block_given?
       content = capture(&block)
     else
       content = ""
     end

     form.label(form.object.errors[attr]) + content + form.label(form_label, class: "control-label")
   end

2 个答案:

答案 0 :(得分:2)

你不能连接这样的字符串。第yield(block) +行不是一个完整的行。这就是你得到错误的原因。以下是两种可能的修复方法:

def wrapper(form, attr, options = {}, &block)
  if block_given?
    return yield(block) + form.label(form_label, class: "control-label")
  end
  form.label(form_label, class: "control-label")
end

或者这个

def wrapper(form, attr, options = {}, &block)
  content = ''
  if block_given?
    content = yield(block)
  end
  content + form.label(form_label, class: "control-label")
end

答案 1 :(得分:1)

您发现错误是因为您在if块中留下了悬空// Check #x $( "#x" ).prop( "checked", true ); // Uncheck #x $( "#x" ).prop( "checked", false );

你可以做这样的事情

+