1

I have a module defined as:

module MyApp
  module Utility
    def Utility.my_method

I want to use that method in several other classes. But I don't want to have to call:

MyApp::Utility.my_method

I would rather just call:

Utility.my_method

Is that reasonable? I've tried include MyApp::Utility and include MyApp to no avail.

RubyRedGrapefruit
  • 12,066
  • 16
  • 92
  • 193
  • Related? http://stackoverflow.com/q/7373027 – Robert Harvey Dec 31 '12 at 17:36
  • `include MyApp` works for me in Ruby 1.9.3. I'm then able to call Utility.my_method. Not using Rails here though. – Matt Hulse Dec 31 '12 at 17:38
  • When you include a module its methods become instance methods of the object, so you can just do `include MyApp::Utility` and then `my_method` instead of `Utility.my_method` – saihgala Dec 31 '12 at 17:39

2 Answers2

2

Well, just assign any alias you want, e.g.:

ShortNameGoesHere = MyApp::Utility
ShortNameGoesHere.my_method
iced
  • 1,562
  • 8
  • 10
0

Here is an example of mixing in my_method to a class:

#myapp.rb
module MyApp
  module Utility
    def my_method
      "called my_method"
    end
  end
end

#test.rb
require './myapp'
class MyClass
  include MyApp::Utility
end

if __FILE__ == $0 then
  m = MyClass.new
  puts m.my_method
end

It sounds like you want to maintain the namespace of the module on the mixed-in method. I have seen attempts to do so (https://stackoverflow.com/a/7575460/149212) but it seems pretty messy.

If you need my_method to be namespaced, you could simply include a module identifier in the method name:

module MyApp
  module Utility
    def util_my_method
      "called my_method"
    end
  end
end
Community
  • 1
  • 1
Matt Hulse
  • 5,496
  • 4
  • 29
  • 37
  • It refuses to work within a class in 1.9.3. Let's say my classname is MyClass, I end up with the error "undefined constant MyClass::Utility. It shouldn't be this hard. – RubyRedGrapefruit Dec 31 '12 at 17:56
  • Are you attempting to mix-in a class method or an instance method? – Matt Hulse Dec 31 '12 at 18:07
  • I wanted it to be a class method, but I've tried it both ways. – RubyRedGrapefruit Dec 31 '12 at 18:15
  • See the updated answer for an example of mixing in an instance method. As far as mixing in class methods, maybe look at http://stackoverflow.com/questions/10692961/inheriting-class-methods-from-mixins – Matt Hulse Dec 31 '12 at 18:24