On Sun, Aug 5, 2012 at 7:48 PM, Andrea Dallera <[email protected]> wrote:
> Unfortunately, I'd like to avoid storing the class in a variable and then
> referring to it because then the code inside what I called Evaluator would
> have to be aware of the mechanics.
> The method Evaluator#evaluate might also
> refer to more than one constant
>From the rest of your posting it's clear that you mean "classes" and
not "constants".
> and, ideally, shouldn't be at all aware that
> one of the constant it's using is not what it originally was defined:
I think you should step back a bit and rethink. Then, what is the
logic you actually want to implement?
> mind that the swap should happen only for a given instance of Evaluator, not
> at the class level, in a way such as
Why then are you insisting on constants? Constants are definitively
the wrong mechanism in this case.
> ev1 = Evaluator.new
> ev2 = Evaluator.new
> ev1.set(A).to(B) #something like this, or worse named ev1.set(A,B) for
> simplicity
> ev1.evaluate #here, A.is_a?(B)#true.
> ev2.evaluate #here, not so
>
> I'm not even sure if that's possible to do in ruby at this point. Opening
> the singleton class (class << ev1) and defining the constant there works (in
> the sense that the singleton class has the constant correctly changed) but
> the methods defined on the class correctly ignore it.
If you want something constantish then I suggest you use a Hash with
Symbols as keys in Evaluator like
class Evaluator
def initialize
@classes = {
:a => A,
:b => B,
}
end
def evaluate
a_instance = @classes[:a].new
...
end
def set_class(label, class_object)
raise "Wrong arguments" unless label.class == Symbol &&
class_object.class == Class
@classes[label] = class_object
end
end
Cheers
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en