Ruby Classes
|
|
|
|
| Articles Reviews Ruby | ||||
| Written by Bogdan V | ||||
| Friday, 26 January 2007 | ||||
Page 1 of 2
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.
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. 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. 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 Instance variables are not directly accessible outside the class. To make them available, write methods that return their values. class Greeterdef 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 |
||||
| Last Updated ( Sunday, 11 February 2007 ) | ||||
| < Prev | Next > |
|---|







