Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Ruby,Rails) Context of SELF in modules and libraries...?

Quick question regarding the use of "SELF" inside a module or library. Basically what is the scope/context of "SELF" as it pertains to a module or library and how is it to be properly used? For an example of what I'm talking about, check out the "AuthenticatedSystem" module installed with "restful_authentication".

NOTE: I'm aware that 'self' equates to 'this' in other languages and how 'self' operates on a class/object, however in the context of a module/library there is nothing to 'self'. So then what is the context of self inside something like a module where there is no class?

like image 814
humble_coder Avatar asked Jun 08 '09 04:06

humble_coder


People also ask

What is self in Ruby on Rails?

self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.

How does self work in Ruby?

The keyword self in Ruby enables you to access to the current object — the object that is receiving the current message. The word self can be used in the definition of a class method to tell Ruby that the method is for the self, which is in this case the class.

What is class << self in rails?

Outside of any class/module/method definitions, self is a main object of the class Object . >> puts self, self.class main Object. Inside a method within a class, self is the object of that class.

What does self refer to in an instance method body?

the method self refers to the object it belongs to. Class definitions are objects too. If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.


1 Answers

In a module:

When you see self in an instance method, it refers to the instance of the class in which the module is included.

When you see self outside of an instance method, it refers to the module.

module Foo   def a     puts "a: I am a #{self.class.name}"   end    def Foo.b     puts "b: I am a #{self.class.name}"   end    def self.c     puts "c: I am a #{self.class.name}"   end end  class Bar   include Foo    def try_it     a     Foo.b # Bar.b undefined     Foo.c # Bar.c undefined   end end  Bar.new.try_it #>> a: I am a Bar #>> b: I am a Module #>> c: I am a Module 
like image 101
Sarah Mei Avatar answered Sep 23 '22 18:09

Sarah Mei