ERB /模仿红宝石的线索

时间:2014-02-13 12:48:49

标签: ruby erb template-engine

最好我希望模板看起来像这样:

interfaces {
  <%= name %> {
    description "<%= description %>";
    mtu <%= mtu %>;
  }
}

但是,如果代码评估为非真值,我希望不打印行。它可能是ERB的破解,在它设置print_line = true并且在用b%&gt;评估代码之后。假设它设置print_line = false,只打印print_line 但似乎改变ERB对此并不是很简单,它读取整个模板,非代码部分作为打印“数据”插入,结果是单个大的ruby代码串,在#result期间作为整体进行评估。我要么需要评估b%&gt;字符串扫描期间的代码,如果它返回true则只插入打印“data”,或者根本不插入或者我需要重新扫描#result中的代码以运行b%&gt;第一

即使使用模板似乎也没有用,如果你最终在代码块中编写所有内容,例如:

interfaces {
  <%= name %> {
    <% if description %>
    description "<%= description %>";
    <% end%>
    <% if mtu %>
    mtu <%= mtu%>;
    <% end%>
  }
}

或:

interfaces {
  <%= name %> {
    <%= "description \"#{description}\";" if description %>
    <%= "mtu #{mtu};" if mtu %>
  }
}

我需要支持各种不同的配置格式,在某些其他配置格式中,它可能是'maximum-transfer-unit&lt;%= mtu&gt;字节。我希望将模板中的所有特定于平台的智能和模板中的实际代码保持在最低限度。在模板之外添加平台无关的复杂性没有问题。

似乎比较常见的用例。在我使用NIHing自己的模板语言或黑客ERB之前,是否有其他模板语言更适合我的用例。还是想念别的什么?

我已经实现了&lt;%b stuff%&gt;的hack如果计算结果为false,则省略整行。 ERB不是为这样的东西设计的,所以它非常脏,而且我可能更好地编写自己的模板语言,除非有人可以建议现有的解决方案,我可以干净地实现类似的东西。
对于有兴趣的人士,hack在这里http://p.ip.fi/-NeJ

结束重新发明轮子:https://github.com/ytti/malline

1 个答案:

答案 0 :(得分:2)

辅助方法

def description_helper(description)
  "description \"#{description}\";" if description
end
def mtu_helper(mtu)
  "mtu #{mtu};" if mtu
end

interfaces {
  <%= name %> {
    <%= description_helper %>
    <%= mtu_helper %>
  }
}

Decorator pattern

class MyObject
  def description
    'some description'
  end
  def mtu
    nil
  end
  module ViewDecorator
    def description
      "description \"#{super}\";" if super
    end
    def mtu
      "mtu #{super};" if super
    end
  end
end

o = MyObject.new
p o.description #=> "some description"
p o.mtu #=> nil
o.extend MyObject::ViewDecorator
p o.description #=> "description \"some description\";"
p o.mtu #=> nil
相关问题