代码之家  ›  专栏  ›  技术社区  ›  Brad

类内的命名空间方法

  •  1
  • Brad  · 技术社区  · 4 年前

    class Clickup
        
        def initialize
            # sets some variables e.g. api token
        end
    
        module Users
    
            def get_all
                # make call to get all users
            end
    
        end
    
        module Lists
    
            def get_all
                # make call to get all lists
            end
    
        end
    end
    

    然后我可以这样写代码:

    clickup = Clickup.new
    
    @users = clickup::users.get_all
    @lists = clickup::lists.get_all
    

    问题是我不知道这是否是可行的,以及如何调用模块中的方法。

    有人知道怎么做吗,或者有更好的方法吗?

    理想情况下,我只想建立clickup类一次,并且需要在类的根中设置变量,以便通过名称空间方法(例如api令牌)访问。

    1 回复  |  直到 4 年前
        1
  •  2
  •   max pleaner    4 年前

    这真的不可行。名称空间仅在类上可用,而在实例级别不可用,因此 Clickup::Users 会有用但是 Clickup.new::Users 不能。你也许可以用一些元编程来实现,但这会有点复杂,并且会使你的代码更难理解。

    不要错误地认为名称空间不仅仅是这样- 命名空间 . 仅仅因为A::B在A中嵌套了B,并不意味着存在B 他们之间的关系。他们有完全不同的状态和行为。

    下面是一个有点类似的方法,可以工作,但它使你不得不重写 initialize 几次。不过,这可能是件好事。这意味着每个类都是独立工作的,并且只能有

    注意,我冒昧地将4-空格缩进改为2,因为这在Ruby中是正常的。

    class Clickup   
      def initialize(config)
        @config = config
      end
    
      def users
        Users.new(@config)
      end
    
      def lists
        Lists.new(@config)
      end
    
      module Users
        def initialize(config)
          @config = config
        end
    
        def get_all
          # make call to get all users
        end
      end
    
      module Lists
        def initialize(config)
          @config = config
        end
    
        def get_all
          # make call to get all lists
        end
      end
    end
    

    用法和你的想法相似:

    clickup = Clickup.new(foo: "bar")
    clickup.users.get_all # calls Users#get_all
    clickup.lists.get_all # calls Lists#get_all
    

    事实上,我只是想起了一件事。。。 :: 事实上 的别名 . . 这不是通常使用的,但从技术上讲,可以使用您想要的确切呼叫签名:

    clickup = Clickup.new(foo: "bar")
    clickup::users.get_all # calls Users#get_all
    clickup::lists.get_all # calls Lists#get_all
    
    推荐文章