Rails class self
this
module Utility
class Options #:nodoc:
class << self
# we are inside Options's singleton class
def parse(args)
end
end
end
end
is equivalent to:
module Utility
class Options #:nodoc:
def Options.parse(args)
end
end
end
A couple examples to help you understand :
class A
HELLO = 'world'
def self.foo
puts "class method A::foo, HELLO #{HELLO}"
end
def A.bar
puts "class method A::bar, HELLO #{HELLO}"
end
class << self
HELLO = 'universe'
def zim
puts "class method A::zim, HELLO #{HELLO}"
end
end
end
A.foo
A.bar
A.zim
puts "A::HELLO #{A::HELLO}"
# Output
# class method A::foo, HELLO world
# class method A::bar, HELLO world
# class method A::zim, HELLO universe
# A::HELLO world
what does class self mean in Rails?
That is the same as
class Post < ActiveRecord::Base
def self.search(q)
# Class Level Method
# search from DB
end
def search2(qq)
# Instance Level Method
# search from DB
end
end
Class methods work on the class (e.g. Post), instance methods works on instances of that class (e.g. Post.new)
Some people like the class << self; code; end;
way because it keeps all class level methods in a nice block and in one place.
Others like to prefix each method with self.
to explicitly know that is a class method not an instance method. It's a matter of style and how you code. If you put all class methods in a block like class << self
, and this block is long enough, the class << self
line might be out of your editor view making it difficult to know that you are in the class instance block.
On the other hand, prefixing each method with self.
and intermixing those with instance methods is also a bad idea, how do you know all the class methods while reading your code.
Pick an idiom which you prefer for your own code base but if you work on an open source project or you collaborate on someone else's code, use their code formatting rule.
class self vs self.method with Ruby: what's better?
class << self
is good at keeping all of your class methods in the same block. If methods are being added in def self.method
form then there's no guarantee (other than convention and wishful thinking) that there won't be an extra class method tucked away later in the file.
def self.method
is good at explicitly stating that a method is a class method, whereas with class << self
you have to go and find the container yourself.
Which of these is more important to you is a subjective decision, and also depends on things like how many other people are working on the code and what their preferences are.
class self idiom in Ruby
First, the class << foo
syntax opens up foo
's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.
a = 'foo'
class << a
def inspect
'"bar"'
end
end
a.inspect # => "bar"
a = 'foo' # new object, new singleton class
a.inspect # => "foo"
Now, to answer the question: class << self
opens up self
's singleton class, so that methods can be redefined for the current self
object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:
class String
class << self
def value_of obj
obj.to_s
end
end
end
String.value_of 42 # => "42"
This can also be written as a shorthand:
class String
def self.value_of obj
obj.to_s
end
end
Or even shorter:
def String.value_of obj
obj.to_s
end
When inside a function definition, self
refers to the object the function is being called with. In this case, class << self
opens the singleton class for that object; one use of that is to implement a poor man's state machine:
class StateMachineExample
def process obj
process_hook obj
end
private
def process_state_1 obj
# ...
class << self
alias process_hook process_state_2
end
end
def process_state_2 obj
# ...
class << self
alias process_hook process_state_1
end
end
# Set up initial state
alias process_hook process_state_1
end
So, in the example above, each instance of StateMachineExample
has process_hook
aliased to process_state_1
, but note how in the latter, it can redefine process_hook
(for self
only, not affecting other StateMachineExample
instances) to process_state_2
. So, each time a caller calls the process
method (which calls the redefinable process_hook
), the behaviour changes depending on what state it's in.
Difference between 'self.method_name' and 'class self' in Ruby
The class << self
notation opens up the eigenclass of an object. An eigenclass is an anonymous class that stores instance-specific behaviour. In the case of a class an eigenclass is sometimes called a metaclass.
Ruby uses eigenclasses to implement so called 'class methods' (also called static methods).
A Class (as moritz stated) is also an Object in Ruby and in so far as it is an object it also has a class. The class of a class in Ruby is called Class
.
A 'class method' in any language is a method in which a class is the receiver - that is the method is directly invoked on the class itself.
However in order for a method to be invoked on a receiver that method must be defined on the class of that receiver. In the case of classes a 'class method' could be implemented as an instance method on the Class
class.
But defining an instance method on Class
would mean that ALL classes get access to that class method which is not ideal.
Enter the eigenclass, as stated before, the eigenclass for an object is a special class that stores the methods unique to that object. In the case of classes the eigenclass subclasses the Class
class and is the direct class of the class.
'class methods' in Ruby therefore are just 'instance methods' defined on the class's eigenclass.
The def MyClass.my_method
notation actually defines my_method
on the eigenclass of MyClass. If you use this notation you can get by (for a while) without actually understanding eigenclasses since you can trick yourself into thinking it is just Ruby's way of defining 'static methods' and continue thinking Ruby's class model is similar to Java's. However, the class << self
notation allows no such interpretation and you must come to terms with the reality of eigenclasses.
In summary, 'class methods' are actually 'instance methods' defined on the eigenclass and the class << self
gives you access to the eigenclass.
For more reading check out these links:
http://banisterfiend.wordpress.com/2008/11/25/a-complete-ruby-class-diagram/
http://banisterfiend.wordpress.com/2008/10/25/the-secret-life-of-singletons/
http://www.klankboomklang.com/2007/09/21/the-singleton-class/
What is self in class self and why is this different from the Class instance that is defining this block of code?
Why is self not the same as MyClass inside of the class << self scope.
Because the class keyword always changes the scope:
class MyClass
puts self #=> MyClass
class <<self
puts self #=>MyClass’s singleton class
end
end
More specifically, why is the method delegate not available to self
inside of class << self?class MyClass
def self.delegate
puts "executing MyClass.delegate()"
end
class <<self
delegate
end
end
--output:--
1.rb:8:in `singleton class': undefined local variable or method `delegate' for #<Class:MyClass> (NameError)
from 1.rb:7:in `<class:MyClass>'
from 1.rb:1:in `<main>'
Note that the following constructs are equivalent:
class MyClass
def self.delegate
puts "executing MyClass.delegate()"
end
end
MyClass.delegate
--output:--
executing MyClass.delegate()
and:
class MyClass
class <<self
def delegate
puts "executing MyClass.delegate()"
end
end
end
MyClass.delegate
--output:--
executing MyClass.delegate()
Therefore, your code is equivalent to:
class MyClass
class <<self
def delegate
puts "executing MyClass.delegate()"
end
delegate
end
end
If you ignore the outer MyClass for a moment, then you defined a class like this:
class <<self
def delegate
puts "executing MyClass.delegate()"
end
delegate
end
That same structure can be replicated like this:
class Dog
def bark
puts “woof”
end
bark
end
which will produce the same type of error:
1.rb:7:in `<class:Dog>': undefined local variable or method `bark' for Dog:Class (NameError)
from 1.rb:1:in `<main>'
When you call a method and you don't specify a receiver, ruby uses whatever object is currently assigned to the self variable as the receiver.
Inside a method, ruby assigns the object that called the method to the self variable. The object that called the method is not the same thing as the class (object) in which the method is defined.
Inside a class, but outside of any method definitions, ruby assigns the class (object) to self.
Note that it is the instances of the Dog class that can call the def's inside the Dog class, e.g. bark(). Similarly, it is the instances of the singleton class that can call the def's inside the singleton class, e.g. delegate()--the singleton class itself cannot call the def's inside the singleton class. The whole reason they are called singleton classes is because singleton classes have only one instance--in your case the one instance of the singleton class is MyClass. As a result, MyClass can call delegate(), but the singleton class cannot call delegate().
I don't understand really what a class method on an eignclass is
however.
Personally, I don't use the term eigenclass
. In my opinion, ruby has made a decision that the term is singleton class
. If you look through the docs for the Object class, there are no method names that have eigenclass
in them, yet there are method names with singleton class
in them.
All objects have a singleton class. A singleton class is an object. Therefore, every singleton class also has a singleton class--which means that the chain of singleton classes is infinite:
class Dog
end
s1 = Dog.singleton_class
puts s1
s2 = s1.singleton_class
puts s2
s3 = s2.singleton_class
puts s3
--output:--
#<Class:Dog>
#<Class:#<Class:Dog>>
#<Class:#<Class:#<Class:Dog>>>
Which means you can do stuff like this:
class Dog
class <<self #s1
class <<self #s2
def greet #Instances of s2 can call greet, and the only instance of s2 is s1.
puts "hello"
end
end
end
end
class Dog
class <<self
#Inside here self = Dog's singleton class = s1
greet #equivalent to Dogs_singleton_class.greet
end
end
--output:--
hello
However, I've never seen anyone use a singleton class of a singleton class (s2) before in their code. I did it once to answer a question a long, long time ago, and nobody had any idea what I was talking about.
There are some method lookup diagrams here, which might prove useful.
class method `self.` within class methods block `class self` in Ruby
Each object in Ruby has its own singleton class. This is where all the methods of instances are defined.
Consider the following example.
class C; end
c1, c2 = C.new, C.new
c1.extend(Module.new { def m1; 42; end })
c1.m1
#⇒ 42
c2.m1
#⇒ NoMethodError: undefined method `m1' for #<C:0x000055cb062e6888>
c1.singleton_class.instance_methods.grep /m1/
#⇒ [:m1]
c2.singleton_class.instance_methods.grep /m1/
#⇒ []
Singleton class is needed to make it possible to extend objects etc.
In Ruby, everything is object. Classes are indeed objects as well. That’s why each class has its own singleton class. And each singleton class has its singleton class.
c1.singleton_class.singleton_class.singleton_class.singleton_class
#⇒ #<Class:#<Class:#<Class:#<Class:#<C:0x000055cb0459c700>>>>>
Methods defined on foo
are stored in the singleton class of foo
. Methods defined on foo
’s singleton class are stored in the singleton class of the singleton class of foo
. And so forth.
It’s not quite practical, but it’s still possible due to how Ruby treats everything as Object
.
In Ruby, in a method defined in class self, why can't a constant defined on the superclass be access without self?
You have encountered a common Ruby gotcha - constant lookup.
The most important concept in constant lookup is Module.nesting
(unlike in method lookup, where the primary starting point is self
). This method gives you the current module nesting which is directly used by the Ruby interpreter when resolving the constant token. The only way to modify the nesting is to use keywords class
and module
and it only includes modules and classes for which you used that keyword:
class A
Module.nesting #=> [A]
class B
Module.nesting #=> [A::B, A]
end
end
class A::B
Module.nesting #=> [A::B] sic! no A
end
In meta programming, a module or class can be defined dynamically using Class.new
or Module.new
- this does not affect nesting and is an extremely common cause of bugs (ah, also worth mentioning - constants are defined on the first module of Module.nesting):
module A
B = Class.new do
VALUE = 1
end
C = Class.new do
VALUE = 2
end
end
A::B::VALUE #=> uninitialized constant A::B::VALUE
A::VALUE #=> 2
The above code will generate two warnings: one for double initialization of constant A::VALUE and a second for reassigning the constant.
If it looks like "I'd never do that" - this also applies to all the constants defined within RSpec.describe
(which internally calls Class.new), so if you define a constant within your rspec tests, they are most certainly global (unless you explicitly stated the module it is to be defined in with self::
)
Now let's get back to your code:
class SubExample < SuperExample
puts Module.nesting.inspect #=> [SubExample]
class << self
puts Module.nesting.inspect #=> [#<Class:SubExample>, SubExample]
end
end
When resolving the constant, the interpreter first iterates over all the modules in Module.nesting
and searches this constant within that module. So if nesting is [A::B, A]
and we're looking for the constant with token C
, the interpreter will look for A::B::C
first and then A::C
.
However, in your example, that will fail in both cases :). Then the interpreter starts searching ancestors of the first (and only first) module in Module.nesting. SubrExample.singleton_class.ancestors
gives you:
[
#<Class:SubExample>,
#<Class:SuperExample>,
#<Class:Object>,
#<Class:BasicObject>,
Class,
Module,
Object,
Kernel,
BasicObject
]
As you can see - there is no SuperExample
module, only its singleton class - which is why constant lookup within class << self
fails (print_constant_fails
).
The ancestors of Subclass
are:
[
SubExample,
SuperExample,
Object,
Kernel,
BasicObject
]
We have SuperExample
there, so the interpreter will manage to find SuperExample::A_CONSTANT
within this nesting.
We're left with print_constant_works_2
. This is an instance method on a singleton class, so self
within this method is just SubExample
. So, we're looking for SubExample::A_CONSTANT
- constant lookup firstly searches on SubExample
and, when that fails, on all its ancestors, including SuperExample
.
Related Topics
Set Tag Attribute and Add Plain Text Content to the Tag Using Nokogiri Builder (Ruby)
How to Inherit Abstract Unit Tests in Ruby
Rails First_Or_Create Activerecord Method
Automatic Logging of Datamapper Queries
Why Don't Ruby Methods Have Lexical Scope
How to Fix Undefined Method 'Split' for Nil:Nilclass Error
How to Modify the Input Type of the Rails Datetime_Select Helper
After Installing a Gem Within a Script, How to Load the Gem
Ruby Escape Argv Argument or String as Argument to Shell Command
Refactoring Activerecord Models with a Base Class Versus a Base Module
Setting Environment Variables with Puppet
Split String Without Removing Delimiter
Xpath Parent Attribute of Selection
How to Use Rails 5.1.0 and Jquery
Raise Exception When Accessing Attributes That Doesn't Exist in Openstruct