开发者

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 m开发者_运维百科odule.

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


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"


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜