On Mon, Apr 11, 2011 at 11:20 AM, Lars Olsson <lasso / 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 insta=
nces?
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?>   attr_reader :options
ruby-1.8.7-p334 :007?>   def initialize options
ruby-1.8.7-p334 :008?>     @options =3D options
ruby-1.8.7-p334 :009?>     end
ruby-1.8.7-p334 :010?>   def self.using options
ruby-1.8.7-p334 :011?>     new(options)
ruby-1.8.7-p334 :012?>     end
ruby-1.8.7-p334 :013?>   end
 =3D> nil
ruby-1.8.7-p334 :014 > foo =3D Opportunities.using({:a =3D> 3, :b =3D> 4})
 =3D> #<Opportunities:0xb7496418 @options=3D{:b=3D>4, :a=3D>3}>
ruby-1.8.7-p334 :015 > foo.options
 =3D> {:b=3D>4, :a=3D>3}
ruby-1.8.7-p334 :016 > bar =3D Opportunities.using({:a =3D> 5, :b =3D> 10})
 =3D> #<Opportunities:0xb748e22c @options=3D{:b=3D>10, :a=3D>5}>
ruby-1.8.7-p334 :017 > bar.options
 =3D> {:b=3D>10, :a=3D>5}

Jesus.