On Tue, Apr 12, 2011 at 4:48 AM, 7stud -- <bbxx789_05ss / yahoo.com> wrote:
> ...but then you could do this:
>
> module ClassFactory
> =A0def ClassFactory.included(includer)
> =A0 =A0includer.extend(ClassMethods)
> =A0end
>
> =A0module ClassMethods
>
> =A0 =A0def using(hash)
> =A0 =A0 =A0Class.new do
> =A0 =A0 =A0 =A0@options =3D hash
> =A0 =A0 =A0 =A0class << self
> =A0 =A0 =A0 =A0 =A0attr_reader :options
> =A0 =A0 =A0 =A0end
> =A0 =A0 =A0end
> =A0 =A0end
>
> =A0end
> end
>
> class Opportunities
> =A0include 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 =3D Opportunities.using(foo: 1, bar: 2)
=3D> #<Class:0x10952bc0>
irb(main):021:0> foo.options
=3D> {:foo=3D>1, :bar=3D>2}
irb(main):022:0> foo.ancestors
=3D> [#<Class:0x10952bc0>, Opportunities, Object, Kernel, BasicObject]

> I really wanted to write that like below, but it doesn't work??
>
> module ClassFactory
> =A0def ClassFactory.included(includer)
> =A0 =A0includer.extend(ClassMethods)
> =A0end
>
> =A0module ClassMethods
>
> =A0 =A0def using(hash)
> =A0 =A0 =A0Class.new do
> =A0 =A0 =A0 =A0@options =3D hash
> =A0 =A0 =A0end
> =A0 =A0end
>
> =A0 =A0def options
> =A0 =A0 =A0@options
> =A0 =A0end
>
> =A0end
> end
>
> class Opportunities
> =A0include ClassFactory
> end
>
> Foo =3D Opportunities.using({one: 1, two: 2, three: 3})
> Bar =3D Opportunities.using({four: 4, five: 5, six: 6})
>
> p Foo.options
> p Bar.options
>
> --output:--
> prog.rb:28:in `<main>': undefined method `options' for Foo:Class
> (NoMethodError)

Your new class does not inherit module ClassMethods, that's why.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/