In the Users/index view, you can automatically make a link to a page by using just one line of code:
<%= will_paginate%>
I did not tell it to change which target array to page, but it can be intelligently positioned to
@users
Variable.
It's amazing, can't help wondering, look at the code
Def will_paginate (collection = nil, options = {})
.
.
.
Collection | | = Infer_collection_from_controller
.
.
End
Discovers that the collection object will pass
Infer_collection_from_controller
To get the default value and continue mining the code.
def Infer_collection_from_controller
collection_name = "@#{controller.controller_name}"
Collection = Instance_variable_get (collection_name)
Raise Argumenterror, "the #{collection_name} variable appears to be empty. Did You "+
"Forget to pass," collection object for Will_paginate? "if Collection.nil?
Collection
End
found that it constructs a variable name with the same name as Controller
@users
, and then through
Instance_variable_get
From the controller instance, find the name
@users
and returns the variable.
Summary: Through
Instance_variable_get
Can we look up an instance variable in the context in which the method is invoked? I'll study it in depth.
Add
Ruby 1.8 Features
Gets and returns the value of an instance variable of an object.
You can use a string or symbol to specify the instance variable name to Var.
Returns nil if the instance variable has not been defined.
Class Foo
DEF initialize
@foo = 1
End
End
obj = foo.new
P Obj.instance_variable_get ("@foo") # => 1
P Obj.instance_variable_get (: @foo) # => 1
P Obj.instance_variable_get (: @bar) # => Nil
Instance_variable_set (Var, val)
Ruby 1.8 Features
Assigns a Val value to an object's instance variable and returns the value.
You can use a string or symbol to set the instance variable name to Var.
If the instance variable has not been defined, redefine it.
obj = object.new
P obj.instance_variable_set ("@foo", 1) # => 1
P obj.instance_variable_set (: @foo , 2 # => 2
P obj.instance_variable_get (: @foo) # => 2