Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby “如何访问”;“全球”;(常数?)类中的capistrano变量?(红宝石)_Ruby_Global Variables_Capistrano - Fatal编程技术网

Ruby “如何访问”;“全球”;(常数?)类中的capistrano变量?(红宝石)

Ruby “如何访问”;“全球”;(常数?)类中的capistrano变量?(红宝石),ruby,global-variables,capistrano,Ruby,Global Variables,Capistrano,所以我在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 :m

所以我在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"
稍后,我可以在名称空间中的函数或任务中访问常量,如:

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
它失败于:

/config/deploy.rb:120:in `some_static_method': undefined local variable or method `my_constant' for #<Class:0x000000026234f8>::SomeClass (NameError)
/config/deploy.rb:120:在'some_static_method'中:未定义的局部变量或方法'my_constant':SomeClass(NameError)
我做错了什么??
谢谢

deploy.rb文件是instance_evaled,这意味着它是在对象的上下文中执行的,因此,在离开该上下文之前,您声明的任何内容都是可用的。一旦您创建了一个提供新上下文的类

为了访问原始上下文,必须将对象(self)传递给类方法

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

虽然我真的不明白你为什么要这样声明一个类,但对它来说这是一个奇怪的地方。

deploy.rb文件是instance\u evaled,这意味着它是在对象的上下文中执行的,因此,在离开该上下文之前,你声明的任何内容都是可用的。一旦您创建了一个提供新上下文的类

为了访问原始上下文,必须将对象(self)传递给类方法

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
虽然我真的不明白为什么要声明这样的类,但这是一个奇怪的地方