random_record 0.0.3 → 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
data/README.mdown CHANGED
@@ -19,13 +19,56 @@ After updating your bundle, you can use Random function within any ActiveRecord
19
19
  For example you can do something like this in your controller (**app/controllers/users_controller.rb**), view or presenter
20
20
 
21
21
  ```ruby
22
- RANDOM_LIMIT = 5
22
+ class UsersController < ApplicationController
23
+ RANDOM_LIMIT = 5
23
24
 
24
- def index
25
- @users = User.random(RANDOM_LIMIT)
25
+ def index
26
+ @users = User.random(RANDOM_LIMIT)
27
+ end
28
+
29
+ def show
30
+ @user = User.random
31
+ end
26
32
  end
33
+ ```
34
+
35
+ ## Advanced Usage
36
+
37
+ **Random Record** is _implemented_ as a **Class Method** within ActiveRecord Models
38
+ and can only be attached to the end of a scope chain as it uses eager loading
39
+
40
+ **What does the mean, _oh not so wise one?_**
27
41
 
28
- def show
29
- @user = User.random
42
+ Rails 3 uses ActiveRecord::Relation for chaining things like scopes, joins, where, or order on your model. This allows Rails to chain these scopes without returning the data until really needed. This is referred to as lazily loading.
43
+
44
+ This creates a contraint on the implementation of `random()` method
45
+
46
+ `random()` method requires eager loading (required data has to be fetched from the database before creating a random set).
47
+
48
+ This allows us the append this random method to the end of any **Arel chain**.
49
+
50
+ ```ruby
51
+ class User < ActiveRecord::Base
52
+ scope :students, where("role = ?", "Student")
30
53
  end
31
- ```
54
+
55
+ class UsersController < ApplicationController
56
+ RANDOM_LIMIT = 5
57
+
58
+ def index
59
+ @users = User.students.order("created_at DESC").random(RANDOM_LIMIT)
60
+ end
61
+
62
+ def show
63
+ @user = User.where("role <> ?", "Student").random
64
+ end
65
+ end
66
+ ```
67
+
68
+ But it restricts us to do something like this _(use this method within a scope chain)_
69
+
70
+ <strike>
71
+ ```ruby
72
+ @user = User.random(2).where("role <> ?", "Student")
73
+ ```
74
+ </strike>
@@ -1,3 +1,3 @@
1
1
  module RandomRecord
2
- VERSION = "0.0.3"
3
- end
2
+ VERSION = "0.0.5"
3
+ end
metadata CHANGED
@@ -2,7 +2,7 @@
2
2
  name: random_record
3
3
  version: !ruby/object:Gem::Version
4
4
  prerelease:
5
- version: 0.0.3
5
+ version: 0.0.5
6
6
  platform: ruby
7
7
  authors:
8
8
  - Rahul Trikha