Class: Plato::DocumentCollection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/plato/document.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sort = nil) ⇒ DocumentCollection

Returns a new instance of DocumentCollection.



66
67
68
69
# File 'lib/plato/document.rb', line 66

def initialize(sort = nil)
  @documents = []
  @sort_attribute, @sort_order = sort.split(' ') if sort
end

Instance Attribute Details

#sort_attributeObject

Returns the value of attribute sort_attribute.



64
65
66
# File 'lib/plato/document.rb', line 64

def sort_attribute
  @sort_attribute
end

#sort_orderObject

Returns the value of attribute sort_order.



64
65
66
# File 'lib/plato/document.rb', line 64

def sort_order
  @sort_order
end

Instance Method Details

#<<(doc) ⇒ Object



71
72
73
74
# File 'lib/plato/document.rb', line 71

def <<(doc)
  @to_a = nil
  @documents << doc
end

#[](*args) ⇒ Object



76
# File 'lib/plato/document.rb', line 76

def [](*args); to_a.[](*args) end

#ascending?Boolean

Returns:

  • (Boolean)


127
128
129
# File 'lib/plato/document.rb', line 127

def ascending?
  sorted? && !descending?
end

#descending?Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/plato/document.rb', line 123

def descending?
  sorted? && !!(sort_order =~ /^desc/i)
end

#each(&block) ⇒ Object



103
104
105
# File 'lib/plato/document.rb', line 103

def each(&block)
  to_a.each(&block)
end

#firstObject



85
86
87
# File 'lib/plato/document.rb', line 85

def first
  to_a.first
end

#index(doc, strict = false) ⇒ Object



78
79
80
81
82
83
# File 'lib/plato/document.rb', line 78

def index(doc, strict = false)
  unless index = to_a.index(doc)
    raise ArgumentError, "document is not a member of this collection" unless strict
  end
  index
end

#next(doc) ⇒ Object



94
95
96
# File 'lib/plato/document.rb', line 94

def next(doc)
  to_a[index(doc) + 1]
end

#prev(doc) ⇒ Object



89
90
91
92
# File 'lib/plato/document.rb', line 89

def prev(doc)
  idx = index(doc)
  idx.zero? ? nil : to_a[idx - 1]
end

#sort!Object



107
108
109
110
111
112
113
114
115
116
117
# File 'lib/plato/document.rb', line 107

def sort!
  @to_a =
    if sorted?
      @documents.sort! do |a, b|
      a,b = [a, b].map {|d| d.send(sort_attribute) }
      ascending? ? a <=> b : b <=> a
    end
    else
      @documents
    end
end

#sorted?Boolean

Returns:

  • (Boolean)


119
120
121
# File 'lib/plato/document.rb', line 119

def sorted?
  !!@sort_attribute
end

#to_aObject



98
99
100
101
# File 'lib/plato/document.rb', line 98

def to_a
  sort! unless @to_a
  @to_a.dup
end