ruby gem bacon源码阅读6
今天早上看些杂书,读到《大学之路》中吴军讲,人生是马拉松,因为很多人毕业后就不学习了,只要学习就有收获。感觉很深 ,于是接着读源码。静下心来。
用法是:
require 'bacon'
describe 'A new array' do
before do
@ary = Array.new
end
it 'should be empty' do
@ary.should.be.empty
@ary.should.not.include 1
end
那describe是什么意思,应该有个方法呀,找了很久,发现如下:
module Kernel
private
def describe(name, &block) Bacon::Context.new(name, &block) end
def shared(name, &block) Bacon::Shared[name] = block end
end
对内核心进行了扩充。所以第6行,可以理解了。
再看Bacon::Context.new(name, &block),又到哪里呢?
class Context
def initialize(name, &block)
@name = name
@before, @after = [], []
return unless name =~ RestrictContext
Bacon.handle_specification(name) { instance_eval(&block) }
end
此处,要执行块了。
可是,
@ary.should.be.empty
前面理解,因为给object加了should方法,所以
@ary.should可以理解,而Should类有be方法,也可以理解到
@ary.should.be
但empty是什么意思?不理解。
今天还是不能理解,但理解又深了一层。
比如读到
def handle_requirement(description)
print "- #{description}"
error = yield
puts error.empty? ? "" : " [#{error}]"
end
就做试验。
def h2
error=yield
p error
end
h2 { x=2;x}
有结果了。
这样慢慢理解。不过有一句:
Shared = Hash.new { |_, name|
raise NameError, "no such context: #{name.inspect}"
}
不知"_"是何变量?看来,还是要读书。