References Polymorphism

16 views
Skip to first unread message

Nicholas Rowe

unread,
Feb 13, 2013, 2:45:33 AM2/13/13
to toystor...@googlegroups.com
Hello-

I have a series of Devices that all extend from a base class.  I would like to be able reference a device without having to know exactly what kind of device is being referenced.  Maybe something like:

class Test
       #...
  reference :device, Device::Base
end

class LoudTest < Device::Base
end

test = Test.new    
test.device = LoudDevice.new

and then be able to assign anything that inherits from Device::Base.  Is it possible to have polymorphic references like this?  Right now I seem to end up with argument errors.

Thanks!
-Nick

Nicholas Rowe

unread,
Feb 14, 2013, 3:08:30 AM2/14/13
to toystor...@googlegroups.com
I ended up foregoing using the reference method and managed the association in my code.  It now looks like this:

class Device
  include Toy::Store

  attribute :device_adapter_id, String

  def device_adapter
    @device_adapter || load_device_adapter
  end

  def device_adapter=(device_adapter)
    self.device_adapter_id = device_adapter.id
    @device_adapter = device_adapter
  end

  private

  def load_device_adapter
    self.device_adapter = (Adapter::Base.read(device_adapter_id) || default_adapter)
  end

  def default_adapter
    Adapter::NilAdapter.new
  end
end

-Nick

John Nunemaker

unread,
Feb 19, 2013, 10:41:54 AM2/19/13
to toystor...@googlegroups.com
Yeah there definitely is no way to do polymorphic out of the box. One thing you could do is namespace all your id's at the adapter level with the type. The caveat is you need to know the type when you are querying for it.
--
You received this message because you are subscribed to the Google Groups "ToyStore/Adapter Gems" group.
To unsubscribe from this group and stop receiving emails from it, send an email to toystoreadapt...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages