Created
November 16, 2009 03:57
-
-
Save santosh79/235714 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#A typical ActiveRecord Model would need to extends ActiveRecord::Base, like so: | |
class Person < ActiveRecord::Base | |
end | |
#And now we have access to class & instance level methods like find & save | |
p = Person.find 1 | |
p.save | |
#A non-inheritance based re-write of the above code - i.e. one that does not require | |
#model objects to inherit from ActiveRecord::Base but rather mixin functionality would look like | |
module Persistable | |
def save | |
$stdout.write "in save" | |
end | |
module ClassMethods | |
def find(num) | |
$stdout.write "in find" | |
#find has to return an instance of the receiver class - the *new* class method can be used for now | |
new | |
end | |
end | |
end | |
#And now - here is how the Person class would mixin the Persistable functionality | |
class Person | |
include Persistable | |
extend Persistable::ClassMethods | |
end | |
#We can reduce the restriction on model objects to remember to both include Persistable and extend | |
#Persistable::ClassMethods by the hook-method included | |
module Persistable | |
def save | |
$stdout.write "in save" | |
end | |
#The hook-method: When this module is included - extend the ClassMethods module to provide | |
#class methods functionality | |
def self.included(cls) | |
cls.extend(ClassMethods) | |
end | |
module ClassMethods | |
def find(num) | |
$stdout.write "in find" | |
#find has to return an instance of the receiver class - the *new* class method can be used for now | |
new | |
end | |
end | |
end | |
#Now the Person class does not need to also extends | |
class Person | |
include Persistable | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment