hurray 0.0.1 → 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/lib/hurray.rb +28 -12
- metadata +1 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 66fc996dcb6ff5de44ceda87d0b9de9df69bbc40
|
4
|
+
data.tar.gz: 2918a2a990f457a1ac33d36192a0814915a888b3
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: a81f7f152f5c3521cb3e163c1e4b886a8191d4a9b57e4f1af81f3edf3b164d8afa1804c03e3ac1c1bb8b54e0a5eee92f70c69d6792c596111ee6afeeefe37e20
|
7
|
+
data.tar.gz: e37f3aabb3a41d24f49cb674194cd7171070807f2f5d7a87a9631becac96cca5ad7d4370c574a67892620ee5dff8d891f303306dd0970d26f01207ed01681edc
|
data/lib/hurray.rb
CHANGED
@@ -3,22 +3,38 @@ module Hurray
|
|
3
3
|
extend ActiveSupport::Concern
|
4
4
|
|
5
5
|
module ClassMethods
|
6
|
-
# Get records ordered according to the
|
6
|
+
# Get records ordered according to the specified with array column order
|
7
7
|
#
|
8
|
-
#
|
9
|
-
# >> User.ordered_with([4,2,6])
|
10
|
-
# => User::ActiveRecord_Relation
|
11
|
-
#
|
8
|
+
# Examples:
|
9
|
+
# >> User.ordered_with(:id, [4,2,6])
|
10
|
+
# => User::ActiveRecord_Relation [#<User id: 4 ...>, #<User id: 2 ...>, #<User id: 6 ...>, #<User id: 1 ...>, ...]
|
11
|
+
#
|
12
|
+
# >> User.ordered_with(:id, [4,2,6], provided_only: true)
|
13
|
+
# => User::ActiveRecord_Relation [#<User id: 4 ...>, #<User id: 2 ...>, #<User id: 6 ...>]
|
14
|
+
#
|
15
|
+
# >> User.ordered_with(:name, %w(Nick Malvin John), provided_only: true)
|
16
|
+
# => User::ActiveRecord_Relation [#<User name: Nick ...>, #<User name: Malvin ...>, #<User name: John ...>]
|
12
17
|
#
|
13
18
|
# Arguments:
|
14
|
-
#
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
+
# column: (Key or String) # DB column
|
20
|
+
# array: (Array) # Custom order
|
21
|
+
# options: (Hash)
|
22
|
+
# povided: (Boolean) # Get records satisfying array values
|
23
|
+
# direction: (Key or String) # :asc or :desc
|
24
|
+
|
25
|
+
def ordered_with(column, array, options = {})
|
26
|
+
direction = options[:direction].to_s.upcase
|
27
|
+
direction = %w(ASC DESC).include?(direction) ? direction : 'ASC'
|
28
|
+
provided_only = options[:provided_only].nil? ? false : options[:provided_only]
|
29
|
+
|
30
|
+
order_clause = "CASE #{column} "
|
31
|
+
array.each_with_index do |el, index|
|
32
|
+
order_clause << sanitize_sql_array(['WHEN ? THEN ? ', el, index])
|
19
33
|
end
|
20
|
-
order_clause << sanitize_sql_array(['ELSE ? END',
|
21
|
-
|
34
|
+
order_clause << sanitize_sql_array(['ELSE ? END ', array.length]) << direction
|
35
|
+
|
36
|
+
return where(column => array).order(order_clause) if provided_only
|
37
|
+
order(order_clause)
|
22
38
|
end
|
23
39
|
end
|
24
40
|
end
|