Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby module as collection of methods

I have a rails app that loads lots of data from some java services. I'm writing a module that will allow me to populate some select boxes with this data and I'm trying to include these properly so I can reference them in my views. Here's my module

module FilterOptions
  module Select

    def some_select
     return "some information"
    end
  end
end

My idea was to include FilterOptions in my application_helper, and I thought I could then reference my methods using Select::some_select This is not the case. I have to include FilterOptions::Select then I can reference the method some_select on its own. I don't want that though as I think it's a bit confusing to someone that may not know that some_select is coming from my own module.

So, how do I write methods of a module that are like public static methods so I can include my main module, and reference my methods using the sub-module namespace like Select::some_select

like image 659
brad Avatar asked Jan 18 '10 15:01

brad


2 Answers

If you define module methods within the context of the module itself, they can be called without import:

module FilterOptions
  module Select
    def self.some_select
     return "some information"
    end
  end
end

puts FilterOptions::Select.some_select
# => "some information"

It is also possible to import one module, and not import the next, refer to it by name instead:

include FilterOptions
puts Select.some_select
# => "some information"
like image 97
tadman Avatar answered Sep 17 '22 16:09

tadman


module_function causes a module function to be callable either as an instance method or as a module function:

#!/usr/bin/ruby1.8

module Foo

  def foo
    puts "foo"
  end
  module_function :foo

end

Foo.foo        # => foo
Foo::foo       # => foo

include Foo
foo            # => foo

Sometimes you want every method in a module to be a "module function," but it can get tedious and repetitive to keep saying "module_function" over and over. In that case, just have your module extend itself:

!/usr/bin/ruby1.8

module Foo

  extend self

  def foo
    puts "foo"
  end

end

Foo.foo        # => foo
Foo::foo       # => foo

include Foo
foo            # => foo
like image 37
Wayne Conrad Avatar answered Sep 21 '22 16:09

Wayne Conrad