2013-06-28 48 views
0

如何指定一個類與Date進行比較?創建一個與Date類相媲美的Ruby類

class FolderDate 

    attr_reader :folder 

    def initialize folder 
    @folder = folder 
    end 
end 

class AsteriskFolderDate < FolderDate 

    include Comparable 

    attr_reader :date 

    def initialize folder 
    super 
    @date = get_date 
    end 

    def <=>(other) 
    @date <=> other 
    end 

    private 
    #omitted 
end 

在Rails控制檯...

AsteriskFolderDate.new("20130628") > Date.today-1 
=> true 
AsteriskFolderDate.new("20130627") > Date.today 
=> false 

規格文件...

describe "An instance of", AsteriskFolderDate do 
    let(:folder) { DateFolder.new(Date.today).asterisk_folder } 

    subject { AsteriskFolderDate.new(folder) } 

    #omitted 

    it "should compare based on @date" do 
    expect(Date.today-1).to be < subject 
    expect(subject).to be > Date.today-1 
    end 
end 

測試失敗...

Failure/Error: expect(Date.today-1).to be < subject 
    ArgumentError: 
    comparison of Date with AsteriskFolderDate failed 

控制檯輸出讓我想認爲它正在工作,但測試失敗。我在正確的軌道上,還是測試指出我在控制檯中缺少的缺陷?

回答

1

問題在於你在比較的順序。如果您在Rails控制檯中執行此操作:

Date.today < AsteriskFolderDate.new("20130627") 

您將看到相同的錯誤。只有你的斷言中的一個將引發錯誤:

it "should compare based on @date" do 
    expect(Date.today-1).to be < subject # Fails 
    expect(subject).to be > Date.today-1 # Works 
end 

這是因爲AsteriskFolderDate知道如何把自己比作日期的,但標準紅寶石Date對象不知道什麼AsteriskFolderDate(預計)。

如果你想比較工作的兩種方式,你需要以某種方式修改Date類。

1

您已在AsteriskFolderDate課程中指定了與Date可比的方法。所以下面只是正常工作:

AsteriskFolderDate.new(Date.today.strftime("%Y%m%d")) > Date.today-1 
#=> true 
AsteriskFolderDate.new((Date.today - 1).strftime("%Y%m%d")) > Date.today 
#=> false 

但是你沒有猴子補丁Date,使其與您的自定義類AsteriskFolderDate相媲美。並且,當您編寫Date.today < AsteriskFolderDate.new("20130627")時,<消息被髮送到Date的實例,但是,Date不知道如何與AsteriskFolderDate進行比較,因此從Date#<引發了參數錯誤。

Date.today-1 < AsteriskFolderDate.new(Date.today.strftime("%Y%m%d")) 
# folder_date.rb:23:in `<': comparison of Date with FolderDate failed (ArgumentError) 
#  from folder_date.rb:23:in `<main>' 
相關問題