在 ruby 中编写条件的正确格式,然后使用 HAML 标记内的字符串插值将输出转换为字符串

Correct format for writing conditionals in ruby and then converting output into string using string interpolation inside HAML tag

我正在修复项目前端 rails 开源项目的 ruby 中的错误。我是 ruby on rails、HAML 等的新手。下面这行代码给我带来了很多麻烦。

我想知道格式化它的正确方法是什么。此外,有没有办法编写一个辅助函数来将条件转换为函数调用?任何帮助将不胜感激。

我尝试了多种格式,但开发人员希望我将 if-else 分成几行。我无法完成这项工作。

6:       %strong =
7:       "#{
8:         - if @enterprise.is_primary_producer
9:           = t('.producer_profile')
10:         - else
11:           = t('.profile')

我希望呈现视图,但我却收到语法错误。

是这样的吗?

%strong
  - if @enterprise.is_primary_producer
    = t('.producer_profile')
  - else
    = t('.profile')

就我个人而言,我会这样做:

- t_key = @enterprise.is_primary_producer ? '.producer_profile' : '.profile'
%strong= t(t_key)

如果你想把它移到一个帮助程序中,只需在 application_helper.rb

中的某个地方定义它
def some_name_for_the_method(enterprise)
  t_key = enterprise.is_primary_producer ? '.producer_profile' : '.profile'
  I18n.t(t_key)
end

和视图

%strong= some_name_for_the_method(@enterprise)