Created
January 10, 2010 23:28
-
-
Save NigelThorne/273858 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
#Taken from http://coderrr.wordpress.com/2008/04/22/building-the-right-class-with-sti-in-rails/ | |
class GenericClass < ActiveRecord::Base | |
class << self | |
def new_with_cast(*a, &b) | |
if (h = a.first).is_a? Hash and (type = h[:type] || h['type']) and (klass = type.constantize) != self | |
raise "wtF hax!!" unless klass < self # klass should be a descendant of us | |
return klass.new(*a, &b) | |
end | |
new_without_cast(*a, &b) | |
end | |
alias_method_chain :new, :cast | |
end | |
end | |
class X < GenericClass; end | |
GenericClass.new(:type => 'X') # => #<X:0xb79e89d4 @attrs={:type=>"X"}> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment