views:

27

answers:

2

I'm working through "Learning Rails by Example" tutorial by Michael Hartl(11.33).The relevant code is:


class PagesController < ApplicationController

def home

@title = "Home"
if signed_in?
  @micropost = Micropost.new
   @feed_items = current_user.feed.paginate(:page => params[:page])
end

end


class User < ActiveRecord::Base

def feed

Micropost.all(:conditions => ["user_id = ?", id])

end


module SessionsHelper

def sign_in(user)

user.remember_me!
cookies[:remember_token] = { :value   => user.remember_token,
                             :expires => 20.years.from_now.utc }
self.current_user= user

end

def current_user=(user)

@current_user = user

end

def current_user

@current_user ||= user_from_remember_token

end


@feed_items is then rendered as a collection to "will_paginate" and everything works fine.

My problem is that I cannot understand how the current_user is passed to the "feed" method in the PagesController line ie

"@feed_items = current_user.feed.paginate(:page => params[:page])"

Any help will be greatly appreciated

Alan

A: 

Most likely "current_user" is defined in the paret class of your controller: ApplicationController. Search for "application_controller.rb" in your controller directory.

Zepplock
Current_user is shown above in SessionsHelper and will return say 44 but how does this get passed to the "feed" method ??Alan
AlanB
A: 

current_user is never "passed" to the feed method - the feed method is called on the current_user object. Take a look at the User model:

def feed
  Micropost.all(:conditions => ["user_id = ?", id])
end

This is an instance method which is executed when you call current_user.feed. The id in the :conditions hash refers to the id of the user object instance, in this case current_user.

StefanO
StefanOThank you so much, its obvious when you explain itI thought current_user had to be an object to do a method callBut further reading shows it can be a variableI have not realized this beforeIs it common? could you point me to any examples?CheersAlan
AlanB
In Ruby, everything is an object, even things which are primitive types in other languages, like integers. So, for example, you can have the following objects:1 - the number one;1.month - the timespan one month;1.month.ago - the datetime corresponding to exactly one month before now.This is quite different from most other languages which I've used. You can read more about the basics here http://www.ruby-lang.org/en/about/
StefanO
StefanOThanks again, a timely reminder for me to review Ruby basicsAlan
AlanB