0
我有一個叫做Votable
模塊,我使用給不同類型的一個votes
屬性和vote_up
和vote_down
方法來定義屬性和排序的集合。不過,我也希望按照其票數排序收集Votable
對象。有沒有一種方法可以使用這個模塊來定義這種排序行爲?模塊通過該屬性
module Votable
attr_reader :votes
def votes
@votes ||= 0
end
def vote_up
@votes += 1
end
def vote_down
@votes -= 1
end
end
class Topic
def initialize
@comments = []
end
def add_comment(comment)
@comments << comment
end
def comments
# this code needs to be duplicated in every class that has a
# collection of votables, but on a different collection
@comments.sort { |a,b| b.votes <=> a.votes }
end
end
class Comment
include Votable
end
在模塊'sort_by_vote' =>'sort {| a,b | b.votes <=> a.votes}' – oldergod