稍有 iOS 开发经验的人应该都是用过 CocoaPods,而对于 CI、CD 有了解的同学也都知道 Fastlane。而这两个在 iOS 开发中非常便捷的第三方库都是使用 Ruby 来编写的,这是为什么?
先抛开这个话题不谈,我们来看一下 CocoaPods 和 Fastlane 是如何使用的,首先是 CocoaPods,在每一个工程使用 CocoaPods 的工程中都有一个 Podfile:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
source 'https://github.com/CocoaPods/Specs.git' target 'Demo' do pod 'Mantle', '~> 1.5.1' pod 'SDWebImage', '~> 3.7.1' pod 'BlocksKit', '~> 2.2.5' pod 'SSKeychain', '~> 1.2.3' pod 'UMengAnalytics', '~> 3.1.8' pod 'UMengFeedback', '~> 1.4.2' pod 'Masonry', '~> 0.5.3' pod 'AFNetworking', '~> 2.4.1' pod 'Aspects', '~> 1.4.1' end |
这是一个使用 Podfile 定义依赖的一个例子,不过 Podfile 对约束的描述其实是这样的:
1 2 3 4 5 6 |
source('https://github.com/CocoaPods/Specs.git') target('Demo') do pod('Mantle', '~> 1.5.1') ... end |
Ruby 代码在调用方法时可以省略括号。
Podfile 中对于约束的描述,其实都可以看作是对代码简写,上面的代码在解析时可以当做 Ruby 代码来执行。
Fastlane 中的代码 Fastfile 也是类似的:
1 2 3 4 5 6 7 8 |
lane :beta do increment_build_number cocoapods match testflight sh "./customScript.sh" slack end |
使用描述性的”代码“编写脚本,如果没有接触或者使用过 Ruby 的人很难相信上面的这些文本是代码的。
Ruby 概述
在介绍 CocoaPods 的实现之前,我们需要对 Ruby 的一些特性有一个简单的了解,在向身边的朋友“传教”的时候,我往往都会用优雅这个词来形容这门语言(手动微笑)。
除了优雅之外,Ruby 的语法具有强大的表现力,并且其使用非常灵活,能快速实现我们的需求,这里简单介绍一下 Ruby 中的一些特性。
一切皆对象
在许多语言,比如 Java 中,数字与其他的基本类型都不是对象,而在 Ruby 中所有的元素,包括基本类型都是对象,同时也不存在运算符的概念,所谓的 1 + 1
,其实只是 1.+(1)
的语法糖而已。
得益于一切皆对象的概念,在 Ruby 中,你可以向任意的对象发送 methods
消息,在运行时自省,所以笔者在每次忘记方法时,都会直接用 methods
来“查文档”:
1 2 |
2.3.1 :003 > 1.methods => [:%, :&, :*, :+, :-, :/, :<, :>, :^, :|, :~, :-<a href='http://www.jobbole.com/members/Famous_god'>@,</a> :**, :<=>, :<<, :>>, :<=, :>=, :==, :===, :[], :inspect, :size, :succ, :to_s, :to_f, :div, :divmod, :fdiv, :modulo, :abs, :magnitude, :zero?, :odd?, :even?, :bit_length, :to_int, :to_i, :next, :upto, :chr, :ord, :integer?, :floor, :ceil, :round, :truncate, :downto, :times, :pred, :to_r, :numerator, :denominator, :rationalize, :gcd, :lcm, :gcdlcm, :+<a href='http://www.jobbole.com/members/Famous_god'>@,</a> :eql?, :singleton_method_added, :coerce, :i, :remainder, :real?, :nonzero?, :step, :positive?, :negative?, :quo, :arg, :rectangular, :rect, :polar, :real, :imaginary, :imag, :abs2, :angle, :phase, :conjugate, :conj, :to_c, :between?, :instance_of?, :public_send, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :private_methods, :kind_of?, :instance_variables, :tap, :is_a?,
这是一个使用 Podfile 定义依赖的一个例子,不过 Podfile 对约束的描述其实是这样的:
Podfile 中对于约束的描述,其实都可以看作是对代码简写,上面的代码在解析时可以当做 Ruby 代码来执行。 Fastlane 中的代码 Fastfile 也是类似的:
使用描述性的”代码“编写脚本,如果没有接触或者使用过 Ruby 的人很难相信上面的这些文本是代码的。 Ruby 概述在介绍 CocoaPods 的实现之前,我们需要对 Ruby 的一些特性有一个简单的了解,在向身边的朋友“传教”的时候,我往往都会用优雅这个词来形容这门语言 除了优雅之外,Ruby 的语法具有强大的表现力,并且其使用非常灵活,能快速实现我们的需求,这里简单介绍一下 Ruby 中的一些特性。 一切皆对象在许多语言,比如 Java 中,数字与其他的基本类型都不是对象,而在 Ruby 中所有的元素,包括基本类型都是对象,同时也不存在运算符的概念,所谓的 得益于一切皆对象的概念,在 Ruby 中,你可以向任意的对象发送
|