Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, inside a class method, is self the class or an instance?

I know that self is the instance inside of an instance method. So, then, is self the class inside of a class method? E.g., Will the following work in Rails?

class Post < ActiveRecord::Base
  def self.cool_post
    self.find_by_name("cool")
  end
end
like image 602
ma11hew28 Avatar asked Dec 03 '10 20:12

ma11hew28


2 Answers

That is correct. self inside a class method is the class itself. (And also inside the class definition, such as the self in def self.coolpost.)

You can easily test these tidbits with irb:

class Foo
  def self.bar
    puts self.inspect
  end
end

Foo.bar  # => Foo
like image 130
Stéphan Kochen Avatar answered Oct 13 '22 17:10

Stéphan Kochen


class Test
    def self.who_is_self
        p self
    end
end

Test.who_is_self

output:

Test

Now if you want a Rails specific solution, it's called named_scopes:

class Post < ActiveRecord::Base
   named_scope :cool, :conditions => { :name => 'cool' }
end

Used like this:

Post.cool
like image 21
krusty.ar Avatar answered Oct 13 '22 17:10

krusty.ar