如何在子类中使用 HTTParty 方法?

发布于 2024-08-21 06:55:45 字数 571 浏览 11 评论 0原文

我正在尝试用 Ruby 编写一个 API 包装器,但对如何从子类调用 HTTParty 方法感到困惑。

我希望用户创建与 API 的连接,然后能够查询子类的结果。

module ApiWrapper
  class Connection
    include HTTParty
    base_uri '...'

    def initialize( u, p )
      ...
    end

    def contacts
      ApiWrapper::Contact
    end
  end
end

module ApiWrapper
  class Contact
    def all
      # issue httparty get request here that is created from the Connection class
    end
  end
end


## The user would do this
conn = ApiWrapper::Connection.new( 'username', 'password' )
contacts = conn.contacts.all

I'm trying to write an API wrapper in Ruby and am stumped on how I can call HTTParty methods from a subclass.

I want the user to create a connection to the API and then be able to query results from subclasses.

module ApiWrapper
  class Connection
    include HTTParty
    base_uri '...'

    def initialize( u, p )
      ...
    end

    def contacts
      ApiWrapper::Contact
    end
  end
end

module ApiWrapper
  class Contact
    def all
      # issue httparty get request here that is created from the Connection class
    end
  end
end


## The user would do this
conn = ApiWrapper::Connection.new( 'username', 'password' )
contacts = conn.contacts.all

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

于我来说 2024-08-28 06:55:45

all() 是一个实例方法,而不是类方法,但您像调用类方法一样调用它。试试这样:

module ApiWrapper
  class Contact
    def self.all
      # issue httparty get request here that is created from the Connection class
    end
  end
end

all() is an instance method, not a class method, but you are calling it like a class method. Try it like this:

module ApiWrapper
  class Contact
    def self.all
      # issue httparty get request here that is created from the Connection class
    end
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文