On 11 Apr, 11:36, Jes=FAs Gabriel y Gal=E1n <jgabrielyga... / gmail.com>
wrote:
> On Mon, Apr 11, 2011 at 11:20 AM, Lars Olsson <la... / lassoweb.se> wrote:
> > Hi list!
>
> > I have a metaprogramming question that is driving me mad. I though I
> > understood how to do it, but obviously I didn't. This is what I want
> > to do:
>
> > I want to create a class method that takes a bunch of options and
> > returns a singleton class with those options set,
>
> > class Opportunities
> > =A0def self.using(options)
> > =A0 =A0# Store options in singleton class variable @options and then
> > return singleton class
> > =A0end
> > =A0def self.options
> > =A0 =A0return @options
> > =A0end
> > end
>
> > So that I can use:
>
> > foo =3D Opportunities.using({:one =3D> 1, :two: =3D> 2, :three =3D> 3})
> > bar =3D Opportunities.using({:four =3D> 4, :five: =3D> 5, :six =3D> 6})
>
> > and then
>
> > foo.options =3D> {:one =3D> 1, :two: =3D> 2, :three =3D> 3}
> > bar.options =3D> {:four =3D> 4, :five: =3D> 5, :six =3D> 6}
>
> > Please note that I don't want instances of the Opportunities class, I
> > want two separate classes that shares the same behavior except for
> > that they return different values for the Opportunities.options call.
>
> If you don't want instances of Opportunities, of which class you want ins=
tances?
> Where is the common behaviour of those objects defined?
>
> > This really should be possible with ruby, right?
>
> I'm not sure if I understand what you want, can you tell us why this
> doesn't fit your requirements:
>
> ruby-1.8.7-p334 :005 > class Opportunities
> ruby-1.8.7-p334 :006?> =A0 attr_reader :options
> ruby-1.8.7-p334 :007?> =A0 def initialize options
> ruby-1.8.7-p334 :008?> =A0 =A0 @options =3D options
> ruby-1.8.7-p334 :009?> =A0 =A0 end
> ruby-1.8.7-p334 :010?> =A0 def self.using options
> ruby-1.8.7-p334 :011?> =A0 =A0 new(options)
> ruby-1.8.7-p334 :012?> =A0 =A0 end
> ruby-1.8.7-p334 :013?> =A0 end
> =A0=3D> nil
> ruby-1.8.7-p334 :014 > foo =3D Opportunities.using({:a =3D> 3, :b =3D> 4}=
)
> =A0=3D> #<Opportunities:0xb7496418 @options=3D{:b=3D>4, :a=3D>3}>
> ruby-1.8.7-p334 :015 > foo.options
> =A0=3D> {:b=3D>4, :a=3D>3}
> ruby-1.8.7-p334 :016 > bar =3D Opportunities.using({:a =3D> 5, :b =3D> 10=
})
> =A0=3D> #<Opportunities:0xb748e22c @options=3D{:b=3D>10, :a=3D>5}>
> ruby-1.8.7-p334 :017 > bar.options
> =A0=3D> {:b=3D>10, :a=3D>5}
>
> Jesus.

Actually, I don't want any instances at all. I would have preferred to
use instances myself, but since my task involves calling a framework
method that takes a class and not an "ordinary" instance I needed a
hack to be override the options method. Robert's solution does exactly
what I need.

Thank you for your speedy answers!

/lasso