Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Created January 10, 2010 23:28
Show Gist options
  • Save NigelThorne/273858 to your computer and use it in GitHub Desktop.
Save NigelThorne/273858 to your computer and use it in GitHub Desktop.
#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