texp是Jim Weirich開發的Ruby臨時表達式庫,提供了模塊化、可擴展的序列化語言。git
臨時表達式提供了一種精煉地表達重複性事件的方式。例如,每一年的12月25日是聖誕節。一個表明聖誕節的臨時表達式會返回真,若是日期是12月25日。github
dec25 = Date.parse("Dec 25, 2008") christmas_texp.includes?(dec25) # => true christmas_texp.includes?(dec25 + 1) # => false
能夠使用運算符組合臨時表達式。例如,若是我有一個聖誕節的臨時表達式和一個感恩節的臨時表達式,我能夠將它們合併成一個假日表達式:segmentfault
holidays_texp = christmas_texp + thanksgiving_texp
TExp
特性基本表達式ruby
複合表達式模塊化
inspect的描述人類可讀編碼
緊湊、可解析的編碼spa
可由用戶擴展的臨時表達式類型code
建構臨時表達式的DSL事件
如下的例子使用了TExp DSL。DSL默認未開啓,能夠經過如下方式開啓:開發
使用全局texp
方法和塊
te = texp { day(1) * month("Jan") }
在類中includeTExp::DSL
模塊
include TExp::DSL te = day(1) * month("Jan")
查看TExp::DSL
模塊獲取全部DSL命令的完整描述。
te = dow(:monday) te.includes?(Date.parse("Mar 3, 2008")) # => true te.includes?(Date.parse("Mar 4, 2008")) # => false te.includes?(Date.parse("Mar 10, 2008")) # => true # 等價於 te = TExp::DayOfWeek.new(Date::DAYNAMES.index("Monday")) # 變體 dow("Mon", "Tues") # 週一或週二
te = month(:march) te.includes?(Date.parse("Mar 1, 2008")) # => true te.includes?(Date.parse("Mar 31, 2008")) # => true te.includes?(Date.parse("Mar 15, 1995")) # => true te.includes?(Date.parse("Feb 28, 2008")) # => false # 等價於 te = TExp::Month.new(3) # 變體 month(1,2,3) # 一月、二月、三月 month("Nov", "Dec") # 十一月或十二月
若是你將臨時表達式當作日期的集合,那麼你能夠以有趣的方式組合這些集合。例如,*
運算符會建立兩個日期集合的交集,只匹配同時知足兩個表達式的日期。
te = day(14) * month("Feb") te.includes?(Date.parse("Feb 14, 2008")) # => true te.includes?(Date.parse("Feb 14, 2007")) # => true # 等價於 te = TExp::And.new( TExp::DayOfMonth.new(14), TExp::Month.new(2))
te = day(14) * month("Feb") * year(2008) te.includes?(Date.parse("Feb 14, 2008")) # => true te.includes?(Date.parse("Feb 14, 2007")) # => false # 等價於 te = TExp::And.new( TExp::DayOfMonth.new(14), TExp::Month.new(2), TExp::Year.new(2008))
交集以外,咱們能夠請求兩個臨時表達式的並集。下面咱們構建一個匹配聖誕節和新年的臨時表達式:
christmas = day(25) * month("Dec") new_years = day(1) * month("Jan") holidays = christmas + new_years holidays.includes?(Date.parse("Jan 1, 2008")) # => true holidays.includes?(Date.parse("Dec 25, 2008")) # => true holidays.includes?(Date.parse("Jan 1, 2009")) # => true holidays.includes?(Date.parse("Feb 14, 2008")) # => false # 等價於 holidays = TExp::Or.new( TExp::And.new( TExp::DayOfMonth.new(25), TExp::Month(12) ), TExp::And.new( TExp::DayOfMonth.new(1), TExp::Month(1) ))
除了月末的週五以外的其餘週五都是Casual Friday:
fridays = dow(:fri) last_friday = week(:last) * dow(:fri) casual_fridays = fridays - last_friday casual_fridays.includes?(Date.new(2013, 6, 21)) # => true casual_fridays.includes?(Date.new(2013, 6, 28)) # => false
編譯 SegmentFault