Created
August 30, 2011 21:21
-
-
Save rmw/1182079 to your computer and use it in GitHub Desktop.
Single Table Inheritance module
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
module SingleTableInheritance | |
def self.included(klass) | |
klass.extend ClassMethods | |
end | |
def class_type=(value) | |
self[:type] = value | |
end | |
def class_type | |
return self[:type] | |
end | |
def after_initialize | |
self.class_type = self.name if self.class_type.nil? | |
end | |
def after_factory(params = {}) | |
end | |
module ClassMethods | |
def factory(params = {}) | |
class_name = params[:type] || params['type'] | |
class_name ||= self.name | |
if defined? class_name.constantize | |
o = class_name.constantize.new(params) | |
else | |
o = self.new(params) | |
end | |
o.class_type = class_name if o.class_type.nil? | |
o.after_factory params | |
o | |
end | |
def factory!(params = {}) | |
o = factory params | |
o.save! | |
o | |
end | |
def call_class_method(class_name, method_name, *args) | |
class_name ||= self.name | |
if defined? class_name.constantize | |
class_name.constantize.method(method_name).call(*args) | |
else | |
self.method(method_name).call(*args) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment