From: lasitha Date: 2009-02-22T03:36:28+09:00 Subject: Re: How to call a module method dynamically On Sat, Feb 21, 2009 at 10:28 PM, Adrian Klingel wrote: > I know about object instantiation and the send method, but the methods I > want to call are not in a class. They live in a module. > > module Foo > > module Bar > > def mymethod > "xyz" > end > > end > > end > > > I can call it statically, like: > > myvar = Foo::Bar::xyz I'm going to assume you meant Foo::Bar::mymethod, but even that wouldn't work. The way you've defined mymethod above makes it an instance method. The only way to access a module instance method is to mix the module into a class/object. If you need an instance method to double as a class method, Module#module_function can help: $: irb 01> module Foo 02> def mymethod; "xyz"; end 03> end --> nil 04> Foo::mymethod NoMethodError: undefined method `mymethod' for Foo:Module from (irb):4 from /usr/local/ruby1.9/bin/irb:12:in `
' 05> module Foo 06> module_function :mymethod 07> end --> Foo 08> Foo::mymethod --> "xyz" Having said all that, you haven't indicated any reason for these be instance methods. If they aren't intended to be mixed into anything and the Module is essentially just a namespace in which to define your methods, they might as well be class methods. If so, then Object#send will work just fine: 09> Foo.send(:mymethod) --> "xyz" > I want to use a single rake task to kick off > any job, so I don't have to have a task for every single job Reconsider. One of the nice things about rake tasks is they double as documentation. Being able to run 'rake -T' and see a listing of available commands is really useful, and more durable than having to remember (or document elsewhere) the names of the available methods. And since rake tasks are created dynamically, some simple reflection and loop will ensure the tasks always match the methods available: namespace :command Foo.methods(false).each do |method_name| desc "run #{method_name}" task method_name do Foo.send(:method_name) end end end I'm still not sure i understand your problem (!), but i hope some part of all the above helps :) lasitha.