Skip to content

Instantly share code, notes, and snippets.

@karmi
Created February 1, 2011 16:59
Show Gist options
  • Save karmi/806150 to your computer and use it in GitHub Desktop.
Save karmi/806150 to your computer and use it in GitHub Desktop.
class Article
attr_reader :filename
def initialize(filename)
@filename = filename
end
def <=> other
self.filename <=> other.filename
end
def inspect
%Q|#<Article filename="#{filename}">|
end
end
class ArticleCollection
include Enumerable
def initialize(database)
@database = database # <<< Implement
@collection = load_collection
end
def << item
item = Article.new(item) unless item.is_a? Article
@collection << item # <<< Implement
self
end
alias :add :<<
def >> item
item = item.filename if item.respond_to? :filename
@collection.reject! { |a| a.filename == item } # <<< Implement
self
end
alias :delete :>>
def [] filename
@collection.select { |a| a.filename == filename }.first
end
alias :find :[]
def <=> other
self <=> other
end
def each(&block)
@collection.each(&block)
end
private
def load_collection # <<< Implement
[]
end
end
coll = ArticleCollection.new('articles') << Article.new('one') << Article.new('two')
puts "~~~ The collection..."
p coll
puts "~~~ Add 'three' and 'four'..."
coll << Article.new('three')
coll.add 'four'
p coll
puts "~~~ Deleting 'three' and 'four'..."
coll >> Article.new('three')
coll.delete 'four'
p coll
puts "~~~ Iteration..."
coll.each_with_index do |a, i|
puts "#{i+1}. #{a.filename}"
end
puts "~~~ Mapping..."
p coll.map { |a| a.filename }
puts "~~~ Accessors..."
p coll['one']
p coll.find 'two'
puts "~~~ Count..."
p coll.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment