---
用类捆绑数据和方法
Classes Bundle Data and Methods
---
# churn-classes.Sub.mine.rb
class SubversionRepository
def initialize(root)
@root = root
end
# 格式化时间
def date(a_time)
a_time.strftime("%Y-%m-%d")
end
# 计算修改次数
def change_count_for(name, start_date)
extract_change_count_from(log(name, date(start_date)))
end
# 根据文本信息(解析字符串)
def extract_change_count_from(log_text)
lines = log_text.split("\n")
dashed_lines = lines.find_all do | line |
line.include?('--------')
end
dashed_lines.length - 1
end
# 使用外部程序获取文本信息
def log(subsystem, start_date)
timespan = "--revision HEAD:{#{start_date}}"
`svn log #{timespan} #{@root}/#{subsystem}`
end
end
# churn-classes.For.mine.rb
class Formatter
def initialize
@lines = []
end
#def use_date(date_string)
# @date_string = date_string
#end
def report_range(from_date, to_date)
@from_date = from_date # 通过实例变量实现封装
@to_date = to_date
end
# 格式化时间
def date(a_time)
a_time.strftime("%Y-%m-%d")
end
def use_subsystem_with_change_count(name, count)
@lines.push(subsystem_line(name, count))
end
def output
ordered_lines = order_by_descending_change_count(@lines)
return ([header] + ordered_lines).join("\n") # 组成字符串数组,并通过join转换成字符串
end
# 处理打印标题信息
def header
"Changes between #{date(@from_date)} and #{date(@to_date)}:"
end
# 组成打印主体信息(参数:子项目,修改次数)
def subsystem_line(subsystem_name, change_count)
asterisks = asterisks_for(change_count)
"#{subsystem_name.rjust(14)} #{asterisks} (#{change_count})"
end
# 计算星号
def asterisks_for(an_integer)
'*' * (an_integer / 5.0).round
end
# 排序
def order_by_descending_change_count(lines)
lines.sort do | first, second |
first_count = churn_line_to_int(first)
second_count = churn_line_to_int(second)
- (first_count <=> second_count)
end
end
def churn_line_to_int(line)
/\((\d+)\)/.match(line)[1].to_i
end
end
# Exercise
# churn-classes.Churn.mine.rb
require 'churn-classes.Sub.mine'
require 'churn-classes.For.mine'
# 处理时间(过去一个月)
def month_before(a_time)
a_time - 28 * 24 * 60 * 60
end
if $0 == __FILE__
subsystem_names = ['audit', 'fulfillment', 'persistence',
'ui', 'util', 'inventory']
root="svn://rubyforge.org//var/svn/churn-demo"
repository = SubversionRepository.new(root)
#start_date = repository.date(month_before(Time.mktime(2005,9,2,0,0,0,0)))
last_month = month_before(Time.mktime(2005,9,2,0,0,0,0))
formatter = Formatter.new
#formatter.use_date(start_date)
formatter.report_range(last_month, Time.mktime(2005,9,2,0,0,0,0))
subsystem_names.each do | name |
formatter.use_subsystem_with_change_count(name,
repository.change_count_for(name, last_month))
end
puts formatter.output
end
** 运行结果 **
>ruby churn-classes.Churn.mine.rb
Changes between 2005-08-05 and 2005-09-02:
ui ** (8)
audit * (5)
util * (4)
persistence * (3)
fulfillment (2)
inventory (2)
>Exit code: 0
** **