简体   繁体   English

ruby模块作为方法的集合

[英]ruby module as collection of methods

I have a rails app that loads lots of data from some java services. 我有一个rails应用程序,从一些Java服务加载大量数据。 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. 我的想法是在我的application_helper中包含FilterOptions,然后我想我可以使用Select::some_select引用我的方法。 Select::some_select并非如此。 I have to include FilterOptions::Select then I can reference the method some_select on its own. 我必须include FilterOptions::Select然后我可以自己引用some_select方法。 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. 我不希望这样,但我认为对于那些可能不知道some_select来自我自己的模块的人来说有点混乱。

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 那么,我如何编写类似公共静态方法的模块方法,以便我可以包含我的主模块,并使用子模块命名空间引用我的方法,如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: 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. 有时你希望模块中的每个方法都是一个“模块函数”,但是一遍又一遍地说“module_function”会变得乏味和重复。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM