Everyday Scripting with Ruby 讀書筆記(4)

[size=small]---
用類捆綁數據和方法
Classes Bundle Data and Methods
---[/size]

# 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


[color=blue][b]** 運行結果 **[/b][/color]
>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
[color=blue][b]** **[/b][/color]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章