26

Cocoapods 源码浅析 - 一些 Tips

 4 years ago
source link: http://saitjr.com/ios/cocoapods-source-code-tips.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在整个源码阅读中,发现很多值得学习的地方,放在某一篇中又不合适,全都汇总在这里吧。

环境信息

Cocoapods 1.9.0.beta.2 (f1293b7)

Core 1.9.0.beta.2 (95e133d)

Podfile 解析

最开始在Podfile 解析最佳实践 中,通过自定义的 pod 等方法,解析 Podfile,从而获取 Podfile 中,每个 pod 的信息。当时有一点没做好:关于解析方法的注入。

起初的做法是这样的:将文件分为了三段,分别是 header.rbPodfilefooter.rb 。定义如下:

# header.rb
$map = {}

def target(target_name = nil, &block = nil)
  yield if block_given?
end

def pod(pod_name, version = nil, **args)
  git = args[:git]
end

def method_missing(m, *args); end

# -----------------------------------------------

#footer.rb
File.open($result_path, "w") do |f|
  f.write(JSON.pretty_generate($map))
end

不难看出,整个解析分为了三个文件,而且最终执行的时候,需要将三个文件按顺序拼接,然后 eval 。除此之外,还有一个弊端:本来解析 Podfile 的脚本就是用 Ruby 写的,最好的通信方式当然是解析完以后,返回一个 map 对象就好。但是在 footer.rb 中可以看到,最后是通过导出文件的形式处理的。

在看 Cocoapods 源码时,发现当初遗漏了一个很重要的点(源码位于 Core/lib/cocoapods-core/podfile.rb 中): include 。源码中,Cocoapods 解析 Podfile 是这样的:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK