在 Rails 3 中包含模块:对于实例方法和类方法(以及 HTTPparty)。

发布于 2024-12-04 06:16:56 字数 768 浏览 0 评论 0原文

我一直想知道如何将类和实例方法放入模块中,然后将该模块包含到模型中。

我已经让它与其他示例一起使用,但我很难理解在哪里正确放置 include HTTPparty.

以下是我所在位置的详细信息:

module Vimeo

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

   class Base      
     include HTTParty
     base_uri 'vimeo.com/api/v2'
     headers 'Content-Type' => 'application/json' 
   end

   class VimeoUser < Base

    def vimeo_account(account_name)
      @id = account_name
    end

   end

 end

   def info
     Vimeo::Base.get("http://vimeo.com/api/v2/#{@id}/info.json")
   end

end

目标是将其附加到用户模型,使用: include Vimeo 并能够致电:

User.vimeo_account("name")

以及

user = User.new
user.info

任何建议,将不胜感激!

I've been wondering about the way to get both class and instance methods into a module, and then including that module into a model.

I've got it working with other examples, but I am struggling to understand where to correctly place the include HTTPparty.

Below is the details of where I am at:

module Vimeo

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

   class Base      
     include HTTParty
     base_uri 'vimeo.com/api/v2'
     headers 'Content-Type' => 'application/json' 
   end

   class VimeoUser < Base

    def vimeo_account(account_name)
      @id = account_name
    end

   end

 end

   def info
     Vimeo::Base.get("http://vimeo.com/api/v2/#{@id}/info.json")
   end

end

with the goal of attaching it to a User model using: include Vimeo
and being able to call:

User.vimeo_account("name")

as well as

user = User.new
user.info

Any advice would be greatly appreciated!

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

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

发布评论

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

评论(1

打小就很酷 2024-12-11 06:16:56

我认为通过以下方式调用 get 应该可以解决问题。

def info
  Vimeo::Base.class.get("http://vimeo.com/api/v2/#{@id}/info.json")
end

但对我来说,你似乎可以有一个更简单的设置,如下所示:
(除非还有更多我不明白的地方)

   class VimeoUser
     include HTTParty
     base_uri 'vimeo.com/api/v2'
     headers 'Content-Type' => 'application/json' 

   // All vimeo user related methods here, such that self.class.get etc is possible.
   end

I think calling get in the following way should solve the problem.

def info
  Vimeo::Base.class.get("http://vimeo.com/api/v2/#{@id}/info.json")
end

But to me it seems like you can have a simpler setup as below:
(unless there is more which I don't understand)

   class VimeoUser
     include HTTParty
     base_uri 'vimeo.com/api/v2'
     headers 'Content-Type' => 'application/json' 

   // All vimeo user related methods here, such that self.class.get etc is possible.
   end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文