如何创建Thor :: Group类变量

时间:2011-10-06 15:19:00

标签: ruby thor

我似乎无法让变量在Thor :: Group中运行。我已经尝试了一些定义常量$ CONFIG $ STAGING_DIR,但它们只是不起作用。

class Package < Thor::Group
include Thor::Actions
attr_accessor :staging_dir, :config
argument :repo, :type => :string, :desc => "The repo to export"
desc "Testing 1.2.3..."

def test_meth
    uri = URI.parse(repo)
    if uri.kind_of?(URI::Generic)
        say "-- Repository seems to be a local directory", :cyan
        if File.exist? repo
            @config = YAML.load_file(repo + "/project.yaml")
            @staging_dir = "/var/tmp/pkg/stage/" + @config["project"]["name"]
            FileUtils.remove_dir @staging_dir if File.exists? @staging_dir
            empty_directory @staging_dir
            directory(repo, @staging_dir)
        end
    end
end

def failure
    puts @config
    puts @staging_dir
end

def self.source_root
    File.dirname(@staging_dir)
end


end
Package.start

./ fubar / var / tmp / test / - 存储库似乎是一个本地目录 零 零

有谁知道如何在Thor :: Group中访问类变量?

1 个答案:

答案 0 :(得分:1)

只需定义一些私有方法。私有方法不会像Thor脚本中的常规方法那样自动执行。方法中的实例变量会在第一次调用方法时评估放在|| =右侧的内容。然后返回结果。此后,它只返回值。因此,您的代码将重写如下:

class Package < Thor::Group
  include Thor::Actions
  attr_accessor :staging_dir, :config
  argument :repo, :type => :string, :desc => "The repo to export"
  desc "Testing 1.2.3..."

  def test_meth
      uri = URI.parse(repo)
      if uri.kind_of?(URI::Generic)
          say "-- Repository seems to be a local directory", :cyan
          if File.exist? repo
              FileUtils.remove_dir staging_dir if File.exists? staging_dir
              empty_directory staging_dir
              directory(repo, staging_dir)
          end
      end
  end

  def failure
      puts config
      puts staging_dir
  end

  def self.source_root
      File.dirname(staging_dir)
  end

  private

  def config
    @config ||= YAML.load_file(repo + "/project.yaml")
  end

  def staging_dir
    @staging_dir ||= "/var/tmp/pkg/stage/" + @config["project"]["name"]
  end

end
Package.start