Module: AttributesSort

Defined in:
lib/attributes_sort.rb

Class Method Summary collapse

Class Method Details

.included(receiver) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/attributes_sort.rb', line 2

def self.included(receiver)
  receiver.instance_eval do
    def do_attributes_sort(collection, attributes)	
		collection.sort_by { |object| attributes.map { |attribute| object.send(attribute) }}				
    end
  end
  Array.class_eval do
	def sortable_attributes?
		self.all? {|object| @attributes.all?{|attribute| object.respond_to?(attribute)}}
	end

    def class_type
      klass = self.first.class
		raise "All objects must respond to sort criteria"unless sortable_attributes?	
      klass
    end

    def attr_sort(options = {})
		@attributes = options[:sort_by]
      raise "You must pass in sort_by criteria" unless @attributes 
      class_type.do_attributes_sort(self, @attributes)
    end
  end
end