如何将当前Basecamp API与ActiveResource一起使用?

exc*_*id3 5 api ruby-on-rails activeresource basecamp ruby-on-rails-3

我正在尝试使用Basecamp Classic API(http://developer.37signals.com/basecamp/comments.shtml).当前的basecamp-wrapper版本给了我适合,其中一个原因是因为json响应包括分页输出,而xml响应包括分页输出.这是一个简单的解决方案,但问题是网址结构不规范.

API指定了一些类似的东西,这使我相信它只是分离出元素路径和集合路径.

Get recent comments (for a commentable resource)
GET /#{resource}/#{resource_id}/comments.xml

Update comment
PUT /comments/#{id}.xml
Run Code Online (Sandbox Code Playgroud)

我已经做了几次尝试,并没有真正成功.尝试处理这样的注释充其量只是hacky,并且实际上并不起作用,因为element_path与collection_path不同.

class Resource < ActiveResource::Base
  self.site = "https://XXXX.basecamphq.com"
  self.user = "XXXX"
  self.password = "X" # This is just X according to the API, I have also read nil works
  self.format = :xml # json responses include pagination crap

  # Override element path so it isn't nested
  class << self
    def element_path(id, prefix_options={}, query_options={})
      prefix_options, query_options = split_options(prefix_options) if query_options.nil?
      "#{collection_name}/#{URI.parser.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
    end
  end
end

class Project < Resource
end

class Message < Resource

  self.element_name = "post"
  self.prefix = "/projects/:project_id/"
  self.collection_name = "posts"

  def comments
    @comments ||= Comment.all(:params => {:resource => "posts" , :resource_id => id})
  end
end

class Comment < Resource
  self.prefix = "/:resource/:resource_id/"
end

puts m = Message.first(:params => {:project_id => PROJECT_ID})
puts m = Message.find(m.id)
puts m.update_attribute(:title, "name")
Run Code Online (Sandbox Code Playgroud)

这工作直到update_attribute,它实际上获得了正确的非嵌套url并且它正在使PUT请求失败.

为什么这不适用于更新?如何以更好的方式处理不同的父资源?

任何提示都会很棒.:)

Ben*_*van 0

如果您尝试破解 ActiveResource,您的日子不会好过。

我不会使用prefix,而是使用 . 在父资源中定义方法来获取子资源find(:all, :from => '')http://api.rubyonrails.org/classes/ActiveResource/Base.html#method-c-find

class Resource < ActiveResource::Base
  self.site = "https://XXXX.basecamphq.com"
  self.user = "XXXX"
  self.password = "X" # This is just X according to the API, I have also read nil works
  self.format = :xml # json responses include pagination crap
end

class Project < Resource
  def messages
    @messages ||= Message.find(:all, :from => "/projects/#{self.id}/posts.xml")
  end
end

class Message < Resource
  self.element_name = "post"

  def comments
    @comments ||= Comment.find(:all, :from => "/posts/#{self.id}/comments.xml")
  end
end

class Comment < Resource
end
Run Code Online (Sandbox Code Playgroud)

您使用这些资源的方式与调用的路径相对应。

project  = Project.find(1)               # GET /projects/1.xml
messages = project.messages              # GET /projects/1/posts.xml
message  = message.first
comments = message.comments              # GET /posts/1/comments.xml
comment.update_attribute(:title,'name')  # PUT /comments/1.xml
Run Code Online (Sandbox Code Playgroud)