Ruby Classes  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews Ruby
Written by Bogdan V   
Friday, 26 January 2007
Article Index
Ruby Classes  Hot
Private and Protected


{mos_sb_discuss:50}

Class definitions start with the keyword class followed by the class name (which must start with an uppercase letter). This Order class is defined to be a subclass of the class Base within the ActiveRecord module.

 



Here’s a Ruby class definition.
Line 1      class Order < ActiveRecord::Base
-
-                 has_many :line_items
-
5                def self.find_all_unpaid
-                      find(:all, 'paid = 0')
-                 end
-
-                def total
10                sum = 0
-                   line_items.each {|li| sum += li.total}
-                end
-            end

 

Rails makes heavy use of class-level declarations. Here has_many is a method that’s defined by Active Record. It’s called as the Order class is being defined. Normally these kinds of methods make assertions about the class, so in this book we call them declarations.

Within a class body you can define class methods and instance methods. Prefixing a method name with self. (as we do on line 5) makes it a class method: it can be called on the class generally. In this case, we can make the following call anywhere in our application.

to_collect = Order.find_all_unpaid

Regular method definitions create instance methods (such as the definition instance methodsof total on line 9). These are called on objects of the class. In the following example, the variable order references an Order object.

We defined the total( ) method in the preceding class definition.

puts "The total is #{order.total}"

Note the difference between the find_all_unpaid( ) and total( ) methods. The first is not specific to a particular order, so we define it at the class level and call it via the class itself. The second applies to one order, so we define it as an instance method and invoke it on a specific order object.


Objects of a class hold their state in instance variables. These variables, whose names all start with @, are available to all the instance methods of a class. Each object gets its own set of instance variables.

class Greeter
      def initialize(name)
          @name = name
      end
      def say(phrase)
           puts "#{phrase}, #{@name}"
     end
end
g1 = Greeter.new("Fred")
g2 = Greeter.new("Wilma")
g1.say("Hello")           #=> Hello, Fred
g2.say("Hi")               #=> Hi, Wilma

 

Instance variables are not directly accessible outside the class. To make them available, write methods that return their values.

class Greeter
       def initialize(name)
           @name = name
        end
        def name
            @name
        end
        def name=(new_name)
            @name = new_name
    end
end
g = Greeter.new("Barney")
puts g.name                #=> Barney
g.name = "Betty"
puts g.name                #=> Betty

Ruby provides convenience methods that write these accessor methods for you (which is great news for folks tired of writing all those getters and setters).

class Greeter
     attr_accessor      :name            # create reader and writer methods
     attr_reader         :greeting        # create reader only
     attr_writer          :age              # create writer only



Last Updated ( Sunday, 11 February 2007 )
 
< Prev   Next >