Flambino
Flambino

Reputation: 18773

Best practice for namespacing functions in Ruby? (novice question)

(StackOverflow is telling me that this question is "subjective and likely to be closed"… well, I'll give it a shot regardless)

I'm writing a bunch of helper methods (for a TextMate bundle), and I'd like (and I need) to have them neatly namespaced.

These methods are really just functions, i.e. they don't operate on anything outside their own scope, and thus don't really belong in a class. There's nothing that needs instantiating.

So far, I've been doing this and that works just fine

module Helpers::Foo
    module_function
    def bar
        # ...
    end
end
Helpers::Foo.bar # this is how I'd like to call the method/function

But would it be better to:
1. Skip module_function and declare the methods/functions as self.*?
2. Or would it be better to declare a class instead of a module?
3. Or use class << self (inside a module or a class)?
4. Or something else entirely?

I realize this is a pretty open-ended question, but I'm really just looking to hear what people are doing.

Upvotes: 11

Views: 1605

Answers (1)

Jed Schneider
Jed Schneider

Reputation: 14671

I prefer either

module Foo
  def self.bar
    "bar"
  end
end

Foo.bar #=> "bar"

or

module Foo
  def Foo.bar
    "bar"
  end
end

Foo.bar #=> "bar"

but probably lean towards the former, i think self. is really descriptive.

Edit: After reading the comments I propose a third option that I prefer for readability. Technically I think this would be defined as extending the methods included on the Eigen class.

module Foo
  module ClassMethods
    def baz
      "baz"
    end
  end
  extend ClassMethods
end

Foo.baz #=> "baz"

Upvotes: 8

Related Questions