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
@current_user ||= Renter.find(session[:user_id]) if session[:user_id]
redirect_to '/login' unless current_user
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 will get/set the instance variable.
But this does not happen by default.
To answer your other question:
: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:
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
def asd return 0 end class Foo def instance_method_bar return 0 end def self.class_method_bar return 0 end end # how the methods are typically called asd Foo.new.instance_method_bar Foo.class_method_bar # another way to call them, using send send(:asd) Foo.new.send(:instance_method_bar) Foo.send(:class_method_bar)
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
Line 7 is the
current_user method being called.