Prev | Current Page 276 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"

The include method works on classes and will affect every instance of that class; the
extend method works on objects themselves and affects only that object.
For the most part, if you want to use a class method, you want the instances of that model
to have some particular behavior. That means you??™ll have to add both class methods and
instance methods. Best practice for making sure both class and instance methods get added is
to separate them out into modules called ClassMethods, InstanceMethods, and SingletonMethods.
CHAPTER 5 ?–  BONUS FEATURES 120
Here??™s a simple skeleton set of modules that will demonstrate the general concepts, using
a module that will allow your models to track and save changes to their fields:
module Auditable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def auditing_columns
@auditing_columns
end
def audits *columns
include Auditable::InstanceMethods
extend Auditable::SingletonMethods
@columns = columns
end
end
module InstanceMethods
end
module SingletonMethods
end
end
The linchpin of this technique is the self.


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