kivanio (owner)

Fork Of

Revisions

gist: 222538 Download_button fork
public
Public Clone URL: git://gist.github.com/222538.git
Embed All Files: show embed
attributes sort.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module AttributesSort
  def self.included(receiver)
    Array.class_eval do
      def do_sort(options = {})
        type = self.first.class
        type.instance_eval do
          def do_attributes_sort(collection, options={})
            attributes = options[:sort_by].inject("["){|attribute_string, attribute| attribute_string << "object.#{attribute},"} + "]"
            collection.sort_by{|object| eval(attributes)}
          end
        end
        type.do_attributes_sort(self, options)
      end
    end
  end
end
 
class Person
  include AttributesSort
 
  attr_accessor :firstname,:lastname,:age
  
  def initialize(firstname,lastname,age=0)
    @firstname = firstname
    @lastname = lastname
    @age = age
  end
 
  def name
    "#{@firstname} #{@lastname}"
  end
 
  def to_s
    "Hello my name is #{name} and my age is #{@age}"
  end
end
 
people = [Person.new("joe","blow",12),Person.new("joe","blow",89),Person.new("mary","watson",32),Person.new("annie","watson",9),Person.new("bob","builder",12)]
 
p people.do_sort(:sort_by=>[:lastname])
puts
p people.do_sort(:sort_by=>[:age])
puts
p people.do_sort(:sort_by=>[:lastname,:firstname,:age])