如何使用Thor模板在范围内制作ruby变量和方法? [英] How do you make ruby variables and methods in scope using Thor Templates?

查看:230
本文介绍了如何使用Thor模板在范围内制作ruby变量和方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Thor :: Actions模板方法生成一些C ++测试文件模板,但是erb不断告诉我我有未定义的变量和方法.

I'm trying to use the Thor::Actions template method to generate some C++ test file templates, but erb keeps telling me that I have undefined variables and methods.

这是呼叫代码:

def test (name, dir)
  template "tasks/templates/new_test_file", "src/#{dir}/test/#{name}Test.cpp"
  insert_into_file "src/#{dir}/test/CMakeLists.txt", 
       "#{dir}/test/#{name}Test ", :after => "set(Local "
end

这是模板:

<% test_name = name + "Test" %>
#include <gtest/gtest.h>
#include "<%= dir %>/<%= name %>.h"

class <%= test_name %> : public testing::Test {
protected:
    <%= test_name %> () {}
    ~<%= test_name %> () {}
    virtual void SetUp () {}
    virtual void TearDown () {}
};

// Don't forget to write your tests before you write your implementation!
TEST_F (<%= test_name %>, Sample) {
   ASSERT_EQ(1 + 1, 3);
}

我该怎么办才能在此处将名称和目录纳入范围?我有更复杂的模板,我也需要此功能.

What do I have to do to get name and dir into scope here? I have more complex templates that I need this functionality for too.

推荐答案

ERB使用ruby的绑定对象来检索所需的变量.红宝石中的每个对象都有一个绑定,但是默认情况下,对绑定的访问仅限于对象本身.您可以解决此问题,并通过创建一个公开对象绑定的模块,将所需的绑定传递到ERB模板中,如下所示:

ERB uses ruby's binding object to retrieve the variables that you want. Every object in ruby has a binding, but access to the binding is limited to the object itself, by default. you can work around this, and pass the binding that you wish into your ERB template, by creating a module that exposes an object's binding, like this:

module GetBinding
  def get_binding
    binding
  end
end

然后,您需要使用此模块扩展具有所需变量的任何对象.

Then you need to extend any object that has the vars you want with this module.

something.extend GetBinding

并将该对象的绑定传递到erb

and pass the binding of that object into erb

something.extend GetBinding
some_binding = something.get_binding

erb = ERB.new template
output = erb.result(some_binding)

有关使用ERB的完整示例,请参见以下Wiki页面查看我的一个项目: https://github.com/derickbailey/Albacore/wiki/Custom-Tasks

for a complete example of working with ERB, see this wiki page for one of my projects: https://github.com/derickbailey/Albacore/wiki/Custom-Tasks

这篇关于如何使用Thor模板在范围内制作ruby变量和方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆