如何从外部静态类访问Capistrano方法?

时间:2013-02-23 18:38:15

标签: ruby deployment capistrano

简单的问题;所以我在capistrano中的deploy.rb脚本看起来像这样,我可以轻松地使用捕获功能:

namespace :mycompany do
    def some_function()
        mylog = capture("some_command")
    end

    desc <<-DESC
        some task description
    DESC
    task :some_task do
        mylog = capture("some_command")
    end
end

但是,如果我在类中使用该方法,如下所示:

namespace :mycompany do
    class SomeClass
        def self.some_static_method()
            mylog = capture("some_command")
        end
    end
end

悲惨地失败了:

/config/deploy.rb:120:in `some_static_method': undefined method `capture' for #<Class:0x000000026234f8>::SomeClass (NameError)

那怎么办?这种方法似乎不是静态的:(它在这里(capistrano来源):

module Capistrano
    class Configuration
        module Actions
            module Inspect

                # Executes the given command on the first server targetted by the
                # current task, collects it's stdout into a string, and returns the
                # string. The command is invoked via #invoke_command.
                def capture(command, options={})
                    ...

1 个答案:

答案 0 :(得分:1)

有人建议以这种方式使用 include

namespace :mycompany do
    class SomeClass
        include Capistrano::Configuration::Actions::Inspect

        def self.some_static_method()
            mylog = self.new.capture("some_command")
        end
    end
end

但是在捕获中出现错误失败了:

/var/lib/gems/1.9.1/gems/capistrano-2.14.2/lib/capistrano/configuration/actions/inspect.rb:34:in `capture': undefined local variable or method `sudo' for #<#<Class:0x00000001cbb8e8>::SomeClass:0x000000027034e0> (NameError)

所以我只是将实例作为参数传递(hacky但它​​有效)。

namespace :mycompany do
    def some_function()
        SomeClass.some_static_method(self)
    end

    class SomeClass
        def self.some_static_method(capistrano)
            mylog = capistrano.capture("some_command")
        end
    end
end

FML