On 12 Apr, 09:00, Robert Klemme <shortcut... / googlemail.com> wrote:
> On Tue, Apr 12, 2011 at 4:48 AM, 7stud -- <bbxx789_0... / 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
> =A0 attr_reader :options
>
> =A0 def using(opts)
> =A0 =A0 Class.new(self).tap do |cl|
> =A0 =A0 =A0 cl.instance_variable_set '@options', opts.freeze
> =A0 =A0 end
> =A0 end
> end
>
> class Opportunities
> =A0 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
>
> --
> remember.guy do |as, often| as.you_can - without endhttp://blog.rubybestp=
ractices.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