AjaxLeung AjaxLeung - 1 year ago 69
Ruby Question

Understanding class variables and methods in Ruby on Rails

I'm new to Ruby and Ruby on Rails, coming from a background of C-like languages.

Here is some code that I found in the


def current_user
@current_user ||= Renter.find(session[:user_id]) if session[:user_id]
helper_method :current_user

def authorize_user
redirect_to '/login' unless current_user

Here is what I don't understand about it:

- On line 4, is
invoking the
instance method, or directly accessing the
instance variable?

- On line 7, is
invoking the
instance method, or directly accessing the
instance variable?

- On line 2, is
a variable or is it more like a string literal being used as a key? Kind of like in JavaScript one might write
to get the
property of the

Answer Source

class methods aren't relevant in this example - they aren't being used here.

Instance variables will never call methods when they are get/set.

Although the opposite does sometimes happen. It's a very common pattern to create getter/setter methods for instance variables, so common that attr reader/writer/accessor helpers are defined in ruby core. If you write attr_accessor :foo, then foo= and foo will get/set the instance variable.

But this does not happen by default.

To answer your other question:

A symbol :user_id starts with a colon and is similar to a string. The difference between a symbol and a string may seem arbitrary, but it is an important concept in Ruby and making the distinction in your head is a good idea.

To respond to your comment:

Line 4, helper_method :current_user is really something specific to rails, consider it "rails magic" if you like. In effect this is making your current_user method callable from views (whereas by default it would only be available in the controller). :current_user is a symbol which is used to reference the current_user method. Not necessarily something you have to understand in total detail, it would suffice to know that helper_method takes a symbol with the same name as a method and makes that method available to views. As far as I'm aware, it's only relevant to Rails controllers.

It's somewhat common in Ruby to use symbols that refer to method names. It's a more intermediate concept. You can see another example in send:

def asd
  return 0

class Foo
  def instance_method_bar
    return 0
  def self.class_method_bar
    return 0

# how the methods are typically called

# another way to call them, using send

I'm not recommending you use send unless you need to, but hopefully it will make it more clear how the symbol :current_user is being used in helper_method

Line 7 is the current_user method being called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download