Ruby module as a set of methods

I have a rails application that loads a lot of data from some java services. I am writing a module that will allow me to populate some of the selection windows with this data, and I am trying to enable them correctly so that I can refer to them in my views. Here is 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 reference my methods using Select::some_select This is not the case. I have to include FilterOptions::Select , then I can reference the some_select method myself. I don't want this, although I think this is a bit confusing to someone who might not know that some_select comes from my own module.

So, how do I write module methods that look like public static methods, so I can turn on my main module and reference my methods using the submodule namespace, for example Select::some_select

+7
ruby module ruby-on-rails
source share
2 answers

If you define module methods in the context of the module itself, you can call them without importing:

 module FilterOptions module Select def self.some_select return "some information" end end end puts FilterOptions::Select.some_select # => "some information" 

You can also import one module, rather than import the following, instead refer to it by name:

 include FilterOptions puts Select.some_select # => "some information" 
+11
source share

module_function calls a module function, which can be called 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 each method in a module to be a “module function”, but it can be tedious and repetitive to keep saying “module_function” again and again. In this case, just expand your module:

 !/usr/bin/ruby1.8 module Foo extend self def foo puts "foo" end end Foo.foo # => foo Foo::foo # => foo include Foo foo # => foo 
+12
source share

All Articles