Created
August 14, 2014 16:51
-
-
Save geoffevason/10755a2e143795e45b95 to your computer and use it in GitHub Desktop.
Code to create an ActiveRecord object by calling create on a base class but actually getting a child class object based on the type attribute provided.
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
class Element < ActiveRecord::Base | |
# This code lets us create the right type of class by passing in :type | |
# eg: Element.new(:type => 'TitleElement') will crteate a TitleElement | |
class << self | |
def class_from_args(a) | |
if (h = a.first).is_a? Hash and (type = h[:type] || h['type']) and (klass = type.constantize) != self | |
raise "Unknown type" unless klass < self # klass should be a descendant of us | |
return klass | |
end | |
end | |
def new_with_cast(*a, &b) | |
klass = class_from_args(a) | |
klass ? klass.new(*a, &b) : new_without_cast(*a, &b) | |
end | |
alias_method_chain :new, :cast | |
def create_with_cast(*a, &b) | |
klass = class_from_args(a) | |
klass ? klass.create(*a, &b) : create_without_cast(*a, &b) | |
end | |
alias_method_chain :create, :cast | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment