Skip to content

Instantly share code, notes, and snippets.

@tylerhunt
Created March 19, 2015 18:52
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerhunt/74a8e1490b9fc4057372 to your computer and use it in GitHub Desktop.
Save tylerhunt/74a8e1490b9fc4057372 to your computer and use it in GitHub Desktop.
An abstract decorator that allows decorated Active Record records to be assigned to associations without raising an ActiveRecord::AssociationTypeMismatch error.
require 'delegate'
# An abstract decorator useful for decorating Active Record objects.
class ActiveRecordDecorator < SimpleDelegator
# A proxy for the decorator class to allow the delegation of certain class
# methods to the decorated object's class.
class ClassProxy < SimpleDelegator
def initialize(decorator_class, decorated_class)
super decorator_class
self.decorated_class = decorated_class
end
# Redefine to allow assignment of decorated Active Record objects to
# associations, which expect `#primary_key` to be defined on the class.
def primary_key
decorated_class.primary_key
end
protected
attr_accessor :decorated_class
end
# Wraps the decorator's class in a proxy to allow decoration of the decorated
# object's class.
def class
ClassProxy.new(super, object.class)
end
# Redefines to avoid ActiveRecord::AssociationTypeMismatch errors when
# assigning decorated Active Record models to associations.
def is_a?(klass)
object.is_a?(klass)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment