From: Lars Olsson Date: 2011-04-12T17:30:41+09:00 Subject: Re: Copying parameters to singleton class On 12 Apr, 09:00, Robert Klemme wrote: > On Tue, Apr 12, 2011 at 4:48 AM, 7stud -- wrote: > > ...but then you could do this: > > > module ClassFactory > >  def ClassFactory.included(includer) > >    includer.extend(ClassMethods) > >  end > > >  module ClassMethods > > >    def using(hash) > >      Class.new do > >        @options = hash > >        class << self > >          attr_reader :options > >        end > >      end > >    end > > >  end > > end > > > class Opportunities > >  include ClassFactory > > end > > I think we can do this simpler if you want to reuse that options > creation functionality: > > module ClassFactory >   attr_reader :options > >   def using(opts) >     Class.new(self).tap do |cl| >       cl.instance_variable_set '@options', opts.freeze >     end >   end > end > > class Opportunities >   extend ClassFactory > end > > irb(main):020:0> foo = Opportunities.using(foo: 1, bar: 2) > => # > irb(main):021:0> foo.options > => {:foo=>1, :bar=>2} > irb(main):022:0> foo.ancestors > => [#, Opportunities, Object, Kernel, BasicObject] > > > > > I really wanted to write that like below, but it doesn't work?? > > > module ClassFactory > >  def ClassFactory.included(includer) > >    includer.extend(ClassMethods) > >  end > > >  module ClassMethods > > >    def using(hash) > >      Class.new do > >        @options = hash > >      end > >    end > > >    def options > >      @options > >    end > > >  end > > end > > > class Opportunities > >  include ClassFactory > > end > > > Foo = Opportunities.using({one: 1, two: 2, three: 3}) > > Bar = Opportunities.using({four: 4, five: 5, six: 6}) > > > p Foo.options > > p Bar.options > > > --output:-- > > prog.rb:28:in `
': undefined method `options' for Foo:Class > > (NoMethodError) > > Your new class does not inherit module ClassMethods, that's why. > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without endhttp://blog.rubybestpractices.com/ Hello again! I've now incorporated your solution into my code and it works very well. I still have a small question though. What's the reason for freezing the options? I can see no obvious explanation for it except that one might not want to change them by accident. Or is there another reason for this? /lasso