From: Trans Date: 2007-06-16T04:13:08+09:00 Subject: Re: Using extend for initialization settings? On Jun 15, 1:05 pm, Robert Klemme wrote: > On 15.06.2007 16:44, Trans wrote: > > > > > It's not uncommon to see initialize method take a hash or a setting > > proc and apply that to accessors. Eg. > > > def initialize( settings ) > > settings.each{|k,v| send("{#k}=",v) > > end > > > or > > > def initialize( &settings ) > > settings.call(self) > > end > > > Today I come up with another potential approach: > > > class Hash > > def to_module(module_function=false) > > m = Module.new > > each do |k,v| > > m.send(:define_method, k){ v } > > m.send(:module_function, k) if module_function > > end > > return m > > end > > end > > > M = { :a => 1 }.to_module(true) > > p M.a #=> 1 > > > class Foo > > def initialize( settings ) > > extend settings.to_module > > end > > end > > > f = Foo.new(:x => 9) > > p f.x #=> 9 > > > Thoughts? > > irb(main):001:0> require 'ostruct' > => true > irb(main):002:0> f = OpenStruct.new(:x => 9) > => # > irb(main):003:0> f.x > => 9 Hmm... I think maybe my point is being missed. The goal is to initialize a class, not create a simple data struct. I think the neat thing about this technique is that it could go beyond just assigning values, and provide a clean means of dependency injection. class Module def to_module; self; end end module Container def log(msg) puts msg end end class Foo def initialize( settings ) extend settings.to_module end def report_ log("Ready.") end end f = Foo.new(Container) f.report produces Ready. T.