Skip to content

Instantly share code, notes, and snippets.

@geoffevason
Created August 14, 2014 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffevason/10755a2e143795e45b95 to your computer and use it in GitHub Desktop.
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.
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