Deleteman
Deleteman

Reputation: 8700

Decorator pattern and type mismatch on ActiveRecord association

I'm using a decorator class to add some functionality to a model of mine. I only want this information to be used to process some values but not to save anything to the database.

I have my decorator class, something like:

class Deco

   def initialize o
     @target = o
   end
   def method_missing method, *args, &block
     @target.send(method, *args, &block)
   end
   #my extra methods
end

And I use it like so:

deco_model = Deco.new(model)

There problem here is when I want to associate this deco_mode to another one, I get a type mismatch error, which makes sense, but if I add the following method to my decorator class:

def class
   @target.class
end

I still get the same error, but it says: Model(#aaaaaa) expected, got Model(#aaaaa) Yes, the "Model" would be the class of my model, and the object id is the same in both cases... so if the object id is the same, why am I still getting the exception?

Thanks

Upvotes: 4

Views: 665

Answers (1)

Deleteman
Deleteman

Reputation: 8700

Turns out I also had to overwrite the is_a? method used inside ActiveRecord::Associaions::Association

After doing:

def is_a? klass
  @target.class.object_id == klass.object_id
end

The exception is not being thrown anymore.

Upvotes: 6

Related Questions