From: Robert Klemme Date: 2011-04-11T18:34:16+09:00 Subject: Re: Copying parameters to singleton class On Mon, Apr 11, 2011 at 11:20 AM, Lars Olsson 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 >  def self.using(options) >    # Store options in singleton class variable @options and then > return singleton class >  end >  def self.options >    return @options >  end > end > > So that I can use: > > foo = Opportunities.using({:one => 1, :two: => 2, :three => 3}) > bar = Opportunities.using({:four => 4, :five: => 5, :six => 6}) > > and then > > foo.options => {:one => 1, :two: => 2, :three => 3} > bar.options => {:four => 4, :five: => 5, :six => 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. > > This really should be possible with ruby, right? Right. You can use a closure like this: class Opportunities def self.using(opts) opts.freeze cl = Class.new self # so we can define instance methods class< foo = Opportunities.using(:one => 1, :two => 2, :three => 3) => # irb(main):020:0> bar = Opportunities.using(:four => 4, :five => 5, :six => 6) => # irb(main):021:0> foo.options => {:one=>1, :two=>2, :three=>3} irb(main):022:0> bar.options => {:four=>4, :five=>5, :six=>6} irb(main):023:0> f = foo.new => #<#:0x109672dc> irb(main):024:0> f.class.options => {:one=>1, :two=>2, :three=>3} irb(main):025:0> f.class.ancestors => [#, Opportunities, Object, Kernel, BasicObject] Or you can use a member class Opportunities def self.using(opts) cl = Class.new self class<