model methods when to use self

I am extending my model with some methods. My question is when to and
when not to define the method with self.

example

def sales_value
  ... all kinds of calculations
end

OR

def self.sales_value
  ... all kinds of calculations
end

The shortest (but not the most correct one) way to describe the
difference is to say that def meth1; end is an object method while def
self.meth2; end is a class method, and you cal them differently:

a = Foo.new
a.meth1
Foo.meth2

But there's more than that

As for Active Records it depends whether you want a method for an
ActiveRecord instance or for the class

Btw these are Ruby basics, find a good Ruby book/tutorial.

Cheers,
Yury

Maybe this will help you.

When you are writing model code you are writing a class. That is
"working class" not "learnstitute class."

Think of "blue collar" and "white collar" workers. People of the
"blue collar" class work a certain way that is difference from a
"white collar" worker. So you may have people (instances) of "blue
collar" and "white" collar workers.

So you have a Class and some Objects of each class. Both the Class
and the Objects can have methods (referred to as class and instance
methods respectively).

When you are writing your code you are writing a class represented in
the def as "self."

So.....

def self.my_class_method
  # Can be called on the Class or instances of the class
end

def my_instance_method
  # Is only available to instances of the class
end

Calling them.....

BlueCollarWorker.my_class_method # called on the class
a_person_object.my_instance_method #called on the instance.

I am extending my model with some methods. My question is when to

  > and when not to define the method with self.

Ruby 101 :

    class String
      def shuffle
        split(//u).sort_by { rand }.join('')
      end

      CHARS = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
      def self.random( len )
          newpass = ""
          1.upto(len) { |i| newpass << CHARS[rand(CHARS.size-1)] }
          return newpass
      end
    end

    puts String.random(10)
    puts "abcdef".shuffle

Alain Ravet

Thanks. great example that makes it clear for me.