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

两盒软妹~` 提交于 2019-12-24 10:49:34

问题


So my deploy.rb script in capistrano starts like this, which I guess is pretty normal:

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


回答1:


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. 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.

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.



来源:https://stackoverflow.com/questions/15043202/how-to-access-global-constant-capistrano-variables-from-classes-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!