ruby - 如何使用 Thor 模板在作用域内创建 ruby​​ 变量和方法?

标签 ruby templates erb thor

我正在尝试使用 Thor::Actions 模板方法生成一些 C++ 测试文件模板,但 erb 一直告诉我我有 undefined variable 和方法。

调用代码如下:

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);
}

我必须做什么才能将 name 和 dir 纳入此处的范围?我有更复杂的模板,我也需要此功能。

最佳答案

我知道你已经解决了这个问题,但我发布这个答案是为了防止其他人出现在寻找你所问问题的解决方案(就像一样)。

在#test 所属的类中,创建一个 attr_accessor,然后在调用模板的相同方法中设置它的值。

class MyGenerator < Thor

  attr_accessor :name, :dir

  def test (name, dir)
    self.name = name
    self.dir = dir
    template "tasks/templates/new_test_file", "src/#{dir}/test/#{name}Test.cpp"
  end
end

注意:如果您使用#invoke 链接方法,那么每次调用都会使用该类的一个新实例。因此,您必须使用模板调用在方法中设置实例变量。例如,以下将不起作用。

class MyGenerator < Thor

  attr_accessor :name

  def one (name)
    self.name = name
    invoke :two
  end

  def two (name)
    # by the time we get here, this is another instance of MyGenerator, so @name is empty
    template "tasks/templates/new_test_file", "src/#{name}Test.cpp"
  end

end

你应该把 self.name = name 放在 #two 里面

为了制作生成器,如果您改为继承自 Thor::Group,则所有方法都会按顺序调用,并且 attr_accessor 将为您设置,并为每个方法设置实例变量。在我的例子中,我不得不使用调用而不是 Thor::Group,因为我无法将 Thor::Group 类识别为可执行文件的子命令。

关于ruby - 如何使用 Thor 模板在作用域内创建 ruby​​ 变量和方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6629967/

相关文章:

ruby - 我怎样才能让 RVM 尊重我的 bundler 关于在哪里放置 gem 的设置?

ruby - 你会如何用 Ruby 和/或 Haskell 编写这个 Clojure 片段?

ruby - 使用 Ruby 处理 PST

c++ - 在 C++ 11 中使用来自模板类型的成员函数指针创建方法参数

c++ - 使用 C++11 类型特征提供替代的内联实现

linux - 将哈希传递给 puppet/erb 中定义的类型

javascript - Rails - js 内的 Asset_path 可能带有变量吗?

ruby - 如何在 rspec 示例中删除全局日志记录功能

c++ - 将 Functor 作为参数传递给方法

css - Rails erb 样式 CSS