【问题标题】:Multiple levels of methods (or dot-notation) in RubyRuby 中的多级方法(或点表示法)
【发布时间】:2011-10-15 18:08:23
【问题描述】:

我看到一个 RubyGem 有以下用途:

f = Foo.new("joe")
f.say.hello #=> "Hello joe"

my Gem 中,我尝试使用相同的语法。我在 Module Dance 中有很多类,但是一旦我创建了 Dance::Client 的新实例,我就无法访问其他类。例如:

d = Dance::Client.new("key")
d::Genres.all # => errors out

我想要的结果是:

d = Dance::Client.new("key")
d.genres.all

【问题讨论】:

    标签: ruby oop rubygems gem


    【解决方案1】:

    您可能有很多方法可以做到这一点,所以这里有几个例子:

    客户端实例方法返回 Genre 类

    module Dance
      class Client
        def genres
          Genre
        end
      end
    
      class Genre
        def self.all
          # return all genres
        end
      end
    end
    

    客户端实例方法返回流派集合类

    module Dance
      class Client
        def genres
          GenreCollection.new
        end
      end
    
      class GenreCollection
        def all
          Genre.all
        end
      end
    
      class Genre
        def self.all
          # return all genres
        end
      end
    end
    

    【讨论】:

      【解决方案2】:

      在你展示的例子中,“say”是一个实例方法,用“hello”方法返回一些东西。

      同样,“流派”是 Dance 模块的客户端实例的实例属性。

      如果您只是尝试实例化一个客户端类,您将使用 Module:: Class 表示法,而您的错误示例尝试使用实例来执行此操作。

      【讨论】:

      猜你喜欢
      • 2012-07-08
      • 1970-01-01
      • 2011-01-14
      • 2013-01-30
      • 2011-08-11
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多