Created
March 19, 2015 18:52
-
-
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.
This file contains hidden or 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
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