Cocoapods RUBY 未定义的局部变量或方法

Cocoapods RUBY undefined local variable or method

我在 Ruby 上还是个新手。我正在尝试编写一些额外的代码来处理我们的 50 个目标 Cocoapods 依赖项。

使用以下代码:

testString = "TEST!!!"

def processPods(platform_name)
    project = Xcodeproj::Project.open "./WhiteLabel.xcodeproj"
    project.targets.each { |target| 
        target_name = target.name
        if target.platform_name == platform_name
            puts "Processing #{target_name} for Platform #{platform_name}"
            puts testString #-->Error ...
        end 
    }
end

#Cocoapods methods
abstract_target 'iOS' do
    puts testString #-->Executes
    processPods(:ios)
end

为了问题,“testString”替换了一个更大的变量。

当我 运行 我得到的代码:

TEST!!!
Processing WhiteLabel for Platform ios

[!] Invalid `Podfile` file: undefined local variable or method `testString' for #<Pod::Podfile:0x00007f8fe11cc2d0>.

 #  from ~/Documents/Developer/Xcode/WhiteLabelApple/Podfile:124
 #  -------------------------------------------
 #              puts "Processing #{target_name} for Platform #{platform_name}"
 >              puts testString
 #          end 
 #  -------------------------------------------

知道为什么吗?

以小写字母开头的变量是本地变量。局部变量在它们定义的范围内是局部的。(因此它们被称为“局部”变量。)

在您的例子中,您正在 脚本范围 中定义一个名为 testString 的局部变量,并试图在方法定义主体的范围内访问它processPods,只是没有定义。

它在底部的块中工作,因为块作用域嵌套。

您可以:

  • processPods
  • 传递一个附加参数
  • 使用块而不是方法定义表达式来定义方法,或者
  • 通过将其名称更改为大写,使变量成为 Object 范围内的 常量变量

如果不想改变量名,可以利用Ruby块是闭包;封闭变量可在块内访问。

test_string = "TEST!!!"

process_pods = lambda do |platform_name|
    project = Xcodeproj::Project.open "./WhiteLabel.xcodeproj"
    project.targets.each { |target| 
        target_name = target.name
        if target.platform_name == platform_name
            puts "Processing #{target_name} for Platform #{platform_name}"
            puts test_string #-->Should work ...
        end 
    }
end

abstract_target 'iOS' do
    puts test_string #-->Executes
    process_pods.call(:ios)
end

有时,无法将变量更改为常量,因为它实际上是变量。因此,将代码放在块中提供了一种组织代码的方式,而不会牺牲对周围变量的访问。