简体   繁体   English

如何从类中访问“全局”(常量?)capistrano变量? (红宝石)

[英]How to access “global” (constant?) capistrano variables from classes? (ruby)

So my deploy.rb script in capistrano starts like this, which I guess is pretty normal: 因此,我在capistrano中的deploy.rb脚本是这样开始的,我认为这很正常:

require 'capistrano/ext/multistage'
require 'nokogiri'
require 'curb'
require 'json'

# override capistrano defaults
set :use_sudo, false
set :normalize_asset_timestamps, false

# some constant of mine
set :my_constant, "foo_bar"

Later, I can access my constant in functions or tasks within namespaces, like: 稍后,我可以访问名称空间中的函数或任务中的常量,例如:

namespace :mycompany do
    def some_function()
        run "some_command #{my_constant}"
    end

    desc <<-DESC
        some task description
    DESC
    task :some_task do
        run "some_command #{my_constant}"
    end
end

However, if I use the constant in a class, like this: 但是,如果在类中使用常量,则如下所示:

namespace :mycompany do
    class SomeClass
        def self.some_static_method()
            run "some_command #{my_constant}"
        end
    end
end

It fails with: 它失败并显示:

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

What am I doing wrong?? 我究竟做错了什么?? Thanks 谢谢

The deploy.rb file is instance_evaled, this means it's being executed inside the context of an object, and as such anything you declare will be available until you leave that context. deploy.rb文件是instance_evaled的,这意味着它正在对象的上下文中执行,因此,声明的任何内容在离开该上下文之前都是可用的。 As soon as you create a class that provides a new context. 一旦创建一个提供新上下文的类。

In order to access the original context you have to pass the object (self) to the class method. 为了访问原始上下文,您必须将对象(自身)传递给class方法。

namespace :mycompany do
  class SomeClass
    def self.some_static_method(cap)
      run "some_command #{cap.fetch(:my_constant)}"
    end
  end

  SomeClass.some_static_method(self)
end

Although I really don't understand why you are declaring a class like this, it's an odd place for it. 尽管我真的不明白为什么您要声明这样的类,但这是一个奇怪的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM