[英]Calling a method inside a do block in ruby
我正在嘗試將所有 git 子模塊中的文件包含在 gemspec 文件中。 gemspec 如下
require File.expand_path(File.dirname(__FILE__)) + '/lib/nameofgem.rb'
# Gets all files, from all submodules, and returns them
# as an array
def getSubmoduleFiles()
files = []
# get an array of submodule dirs by executing 'pwd' inside each submodule
`git submodule --quiet foreach pwd`.split("\n").each do |submodule_path|
gemRootDir = File.dirname(File.expand_path(__FILE__))
# for each submodule, change working directory to that submodule
Dir.chdir(submodule_path) do
submodule_files = getSubmoduleFiles()
# issue git ls-files in submodule's directory
submodule_files + `git ls-files`.split("\n")
puts "found:"
puts submodule_files.to_s
puts
# prepend the submodule path to create absolute file paths
submodule_files_fullpaths = submodule_files.map do |filename|
"#{submodule_path}/#{filename}"
end
# remove leading path parts to get paths relative to the gem's root dir
# (this assumes, that the gemspec resides in the gem's root dir)
submodule_files_paths = submodule_files_fullpaths.map do |filename|
filename.gsub "#{gemRootDir}/", ""
end
# add relative paths to gem.files
files += submodule_files_paths
end
end
return files
end
Gem::Specification.new do |s|
s.name = 'name'
s.version = "1.1.1"
s.executables << 'exec'
s.licenses = ['LICENCE']
s.summary = "Does stuff"
s.description = "Longer description of stuff"
s.authors = ["author"]
s.email = 'my@email'
s.files = `git ls-files -- lib/*`.split("\n")
s.homepage = 'https://example.com/'
s.required_ruby_version = '>= 2.0.0'
s.files += getSubmoduleFiles()
end
但是在 do 塊中,我得到
Invalid gemspec in [nameofgem.gemspec]: undefined method `getSubmoduleFiles' for Gem::Specification:::Module
我究竟做錯了什么? 為什么不能從 do 塊中調用該函數?
似乎 gemspec 文件在作用域和命名空間方面做了一些奇怪的事情(在整個文件中,而不僅僅是在 gemspec 塊本身內),但是在我的頭撞在我的桌子上 15 分鍾后,又喝了一口啤酒以減輕對存在的折磨由於我無法在 gemspec 中調用函數,我想出了一個相當干凈的解決方案:只是堅持self.
在定義和調用中的函數名前面,像這樣:
def self.foo
puts 'It works :)'
end
Gem::Specification.new do |s|
# ...
self.foo # should print 'It works :)' instead of erroring out
# ...
end
為什么這是必要的,為什么在萬維網上的任何地方似乎都沒有其他人問過或回答過這個問題,我沒有最模糊的想法,但我們走了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.