¿Cuál es la mejor manera de anular los métodos en una instancia?

If I were to grab a field out of a database that has a built in wrapper, I'll receive the data as an array of objects, with each object having a series of instances that can be called upon. So for example:

class DataWrapper
  attr_reader :foo, :bar

And the data is returned like [@data1, @data2, @data3, etc] where @data[1-3] are all instances of DataWrapper.

So what if I receive that data before I know what context it's going to be used in, and how I want to format it. What is the best (non-Rails) way to format the data given specific contexts, such as

case :xml
   @data1.to_xml.foo #foo = 4
case :web_table
   @data1.to_web_table.foo #foo = "four"

preguntado el 08 de noviembre de 11 a las 18:11

2 Respuestas

It sounds like you have an array of objects of BaseClass, and you want to later mutate the instances to be some sub-class of BaseClass. You cannot do this. What you can do instead are create modules for each "subclass" representation, and mix them into the the instances on demand.

If you have an array of objects and you want to modify the instances to mix in a particular module:

array.each{ |o| o.extend(MyModule) }

Por ejemplo:

Nib = Struct.new :val do
  def to_s
    value # Must be implemented by instance/subclass

module Nib::Precise
  def value; "%.1f" % val; end

module Nib::Rough
  def value; val.round.to_s; end

module Nib::Ballpark
  def value; ((val/10).round * 10).to_s; end

nibs = [ Nib.new(33.7), Nib.new(29.1) ]

nibs.each{ |n| n.extend(Nib::Precise) }
p nibs.join(", ") #=> "33.7, 29.1"

nibs.each{ |n| n.extend(Nib::Rough) }
p nibs.join(", ") #=> "34, 29"

nibs.each{ |n| n.extend(Nib::Ballpark) }
p nibs.join(", ") #=> "30, 30"

respondido 09 nov., 11:00

I've edited my answer based on your comment to @LarryK; is this what you needed? - Phrogz

The "formatting" methods should probably be last. Eg

case :xml
  @data1.foo.to_xml #foo = 4
case :web_table
  @data1.foo.to_web_table #foo = "four"

You'll need to mixin the formatting methods to the base classes or to Object.

The formatting methods can examine the class of the parent class and decide how to convert the value.

respondido 08 nov., 11:23

This is along the lines of what I'm looking for, but how do I dynamically include the mixin? - Jeremy Smith

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.