Prev | Current Page 275 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

We can use them to add functionality to a model the same way Active Record does.
Your plain basic class method is typically defined in a class by prefixing either the class
name or self to the name of a method:
class ActiveRecord::Base
def self.print_args(*args)
p args
end
end
Then, you can execute the following code:
class Cow < ActiveRecord::Base
print_args [1,2,3], { :one => 1 }
end
and it will print out this:
[[1,2,3], {:one => 1}]
For the most basic case, the preceding example shows all you need to do to add a method
that can be called inside the class definition to a model. In practice, things should be a little
more complicated, because well, hopefully what you want to do is more complicated.
?– Note There is a subtle difference between the include and extend methods. If you include a module
in your class, the methods defined inside that module will act as though they were defined inside the class.
Basically, if you include a module, those methods will be accessible to instances of that class. If you
extend an object with a module, then the methods defined in the module will be available to that object and
that object only.


Pages:
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287