From: "Jesús Gabriel y Galán" Date: 2012-09-27T05:45:18+09:00 Subject: Re: Adding method on module class to yield and allow setting of attributes? On Wed, Sep 26, 2012 at 10:41 PM, Gary Weaver wrote: > 7stud -- wrote in post #1077677: >>> MyModule.configure do >>> foo = false >>> end >> >> That just creates a block local variable which is destroyed when the >> block ends. > > Is there a way to make things in the block execute as if they were being > called on MyModule, i.e. > > MyModule.foo = 1 > MyModule.bar = 2 > > could be alternatively: > > MyModule.do > foo = 1 > bar = 2 > end > >> You could do this: >> >> >> module MyModule >> class <> attr_accessor :foo >> >> def configure(hash) >> hash.each {|key, val| send(:"#{key}=", val)} >> end >> end >> >> end >> >> p MyModule.foo >> MyModule.configure 'foo' => false >> p MyModule.foo >> >> --output:-- >> nil >> false > > That is helpful, but I have a way to do a hash easily already via > another method, with the idea that the following might be interesting: > > MyModule.do > foo = 1 > def bar > 2 # imagine a more interesting and dynamic result > end > end > > I understand it might require some changes, so syntax might not be > exactly like that, but originally I thought this would be doable, and am > just kind of stuck. Ilia had suggested ActiveSupport::Configurable on > the list but it requires config to be sent in as a parameter and I was > hoping to allow method definition and not have to specify the > config.varname = ... I don't know if my previous message got through. If you can handle some changes in the syntax, using self. before the attributes and the method names should work if you do a class_eval: 1.9.2p290 :013 > module MyModule 1.9.2p290 :014?> class << self 1.9.2p290 :015?> attr_accessor :foo 1.9.2p290 :016?> alias_method :foo?, :foo 1.9.2p290 :017?> def configure(&blk) 1.9.2p290 :018?> class_eval(&blk) 1.9.2p290 :019?> end 1.9.2p290 :020?> end 1.9.2p290 :021?> end => nil 1.9.2p290 :022 > MyModule.configure do 1.9.2p290 :023 > def self.test; puts "test"; end 1.9.2p290 :024?> end => nil 1.9.2p290 :025 > MyModule.test test => nil Jesus.