Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use class as method

Tags:

ruby

I like how you instantiate a URI object using the name of the URI class:

uri = URI('https://www.example.com')

Very neat and simple. How do you do that?

For example, suppose I have a module:

module MyModule
   def self.mymethod()
   end
end

MyModule.mymethod is the only method in the module. It's annoying that every time I want that method I have to type:

MyModule.mymethod()

It works, but it seems redundant... it's the only method in the module. Is there a way to only have to call MyModule?

MyModule.mymethod()
like image 935
tscheingeld Avatar asked Mar 14 '19 17:03

tscheingeld


2 Answers

If you look at the source closely you’ll find this:

module Kernel

  #
  # Returns +uri+ converted to an URI object.
  #
  def URI(uri)
    # ...
  end
  module_function :URI
end

Maybe disappointing to you, but if you do URI('https://www.example.com') you just call a method inherited from kernel.

like image 198
idmean Avatar answered Sep 29 '22 06:09

idmean


In your example, URI is just a method named URI. As idmean shows in their answer, it's defined as a module_function in Kernel, which makes it available everywhere, and there are probably good reasons for doing it that way, but just defining it as a normal method in the main scope will accomplish largely the same thing:

def MyModule
  puts "Called MyModule"
end

MyModule()
# => Called MyModule

See it in action on repl.it: https://repl.it/@jrunning/SnowHauntingLevels

like image 25
Jordan Running Avatar answered Sep 29 '22 07:09

Jordan Running