Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Model method self. vs plain

When looking at methods in Rails models, sometimes I see self.method_name and sometimes just a method_name. What's the difference and what is the guide to know when to use self. and when not to?

like image 204
bachposer Avatar asked Feb 26 '12 00:02

bachposer


2 Answers

self.method_name indicates a class method; method_name indicates an instance method.

You can read a lot more about class and instance methods at this blog post or, if you'd prefer something a bit more official, the Programming Ruby class section.

like image 145
Veraticus Avatar answered Oct 04 '22 14:10

Veraticus


1) When applied to method definitions, 'self.' will make it a class method, while plain will be an instance method.

2) When applied to attributes in a model, it's important to always use the self when changing an attribute, but you won't need it otherwise.

so for example:

def some_method  self.name = new_value # correct  name = new_value # will not change the attribute end 
like image 28
Forrest Avatar answered Oct 04 '22 14:10

Forrest