On Wed, Sep 26, 2012 at 9:50 PM, Gary Weaver <lists / ruby-forum.com> wrote:
> I have this Module:
>
> module MyModule
>   class << self
>     attr_accessor :foo
>     alias_method :foo?, :foo
>   end
> end
>
> I can do:
>
> MyModule.foo # nil
> MyModule.foo = true
> MyModule.foo # true
>
> I would like to be able to do this:
>
> MyModule.configure do
>   foo = false
> end
>
> Such that MyModule.foo would then return false:
>
> MyModule.foo # false
>
> I'm a little tired so I'm probably making a mistake:
>
> module MyModule
>   class << self
>     attr_accessor :foo
>     alias_method :foo?, :foo
>     # def configure(&block); yield; end # doesn't work
>   end
> end
>
> # doesn't work either
> #class << MyModule
> #  def configure(&block); yield; end
> #end
>
> Thanks in advance for any advice. I'd rather not use any
> Active*/Rails-specific method and don't want to use Struct, OpenStruct,
> etc. I just want to be able to call the methods created by the
> attr_accessor I used to set and get attributes. The reasons I'm doing
> this to a module and not a class is it is convenient since it is the
> module that my Gem's classes use.

This works:

1.9.2p290 :011 > module MyModule
1.9.2p290 :012?>     class << self
1.9.2p290 :013?>         attr_accessor :foo
1.9.2p290 :014?>         alias_method :foo?, :foo
1.9.2p290 :015?>     def configure(&blk)
1.9.2p290 :016?>       class_eval(&blk)
1.9.2p290 :017?>       end
1.9.2p290 :018?>     end
1.9.2p290 :019?>   end
 => nil
1.9.2p290 :020 > MyModule.configure {self.foo=false}
 => false
1.9.2p290 :021 > MyModule.foo
 => false
1.9.2p290 :022 > MyModule.configure {self.foo=true}
 => true
1.9.2p290 :023 > MyModule.foo
 => true

I don't know if adding the self. is too bad for you. You could also
yield the module itself:

1.9.2p290 :001 > module MyModule
1.9.2p290 :002?>     class << self
1.9.2p290 :003?>         attr_accessor :foo
1.9.2p290 :004?>     alias_method :foo?, :foo
1.9.2p290 :005?>     def configure(&blk)
1.9.2p290 :006?>       yield self
1.9.2p290 :007?>       end
1.9.2p290 :008?>     end
1.9.2p290 :009?>   end
 => nil
1.9.2p290 :010 > MyModule.foo
 => nil
1.9.2p290 :011 > MyModule.configure {|m| m.foo = false}
 => false
1.9.2p290 :012 > MyModule.foo
 => false

Jesus.