无法调用模块方法
Can't call module method
我正在编写一本 Chef 说明书来部署和应用以及创建用户。它没有 API,并且使用了一种奇怪的散列方法,所以我为它编写了一个简短的库模块。为了简洁起见,我在下面仅包括了 makeSalt()
方法。
module Foo_packagist
module Password
def makeSalt(len=31)
require 'securerandom'
return Digest.hexencode(SecureRandom.random_bytes((len*6/8.0).ceil)).to_i(16).to_s(36)[0..len-1]
end
end
end
麻烦的是,在每个 Chef 运行 中,我得到:
NoMethodError
-------------
undefined method `makeSalt' for Foo_packagist::Password:Module
并在 chef-shell
中调试我得到:
chef (12.4.0)> puts ::Foo_packagist::Password.instance_methods()
makeSalt
encodePassword
chef (12.4.0)> puts ::Foo_packagist::Password.makeSalt()
NoMethodError: undefined method `makeSalt' for Foo_packagist::Password:Module
chef (12.4.0)> puts ::Foo_packagist::Password::makeSalt()
NoMethodError: undefined method `makeSalt' for Foo_packagist::Password:Module
调用此方法的正确方法是什么?
将其更改为 def self.makeSalt
。这是模块级方法的 Ruby 语法。
试试这个 ->
module Foo_packagist
module Password
def self.makeSalt(len=31)
require 'securerandom'
return Digest.hexencode(SecureRandom.random_bytes((len*6/8.0).ceil)).to_i(16).to_s(36)[0..len-1]
end
end
end
那么调用它就是这个->
Foo_packagist::Password.makeSalt()
我正在编写一本 Chef 说明书来部署和应用以及创建用户。它没有 API,并且使用了一种奇怪的散列方法,所以我为它编写了一个简短的库模块。为了简洁起见,我在下面仅包括了 makeSalt()
方法。
module Foo_packagist
module Password
def makeSalt(len=31)
require 'securerandom'
return Digest.hexencode(SecureRandom.random_bytes((len*6/8.0).ceil)).to_i(16).to_s(36)[0..len-1]
end
end
end
麻烦的是,在每个 Chef 运行 中,我得到:
NoMethodError
-------------
undefined method `makeSalt' for Foo_packagist::Password:Module
并在 chef-shell
中调试我得到:
chef (12.4.0)> puts ::Foo_packagist::Password.instance_methods()
makeSalt
encodePassword
chef (12.4.0)> puts ::Foo_packagist::Password.makeSalt()
NoMethodError: undefined method `makeSalt' for Foo_packagist::Password:Module
chef (12.4.0)> puts ::Foo_packagist::Password::makeSalt()
NoMethodError: undefined method `makeSalt' for Foo_packagist::Password:Module
调用此方法的正确方法是什么?
将其更改为 def self.makeSalt
。这是模块级方法的 Ruby 语法。
试试这个 ->
module Foo_packagist
module Password
def self.makeSalt(len=31)
require 'securerandom'
return Digest.hexencode(SecureRandom.random_bytes((len*6/8.0).ceil)).to_i(16).to_s(36)[0..len-1]
end
end
end
那么调用它就是这个->
Foo_packagist::Password.makeSalt()