2009 年 1 月 27 日,星期二

自动加载 ActiveResource 模式

发布者:rick

在芝加哥的 Rails 核心黑客马拉松期间,我刚刚提交了一个小功能:自动加载 ActiveResource 模式。注意:这在我的个人分支上,该分支与 rails 仓库同步,并且很可能会被合并到 Rails 2.3 中。

我收到了一些请求,希望解决在使用 Rails 应用中的 form_for 助手时,使用 Lighthouse::Ticket 记录时遇到的问题。这个想法是,资源可以自动只加载一次起始 XML,就像 ActiveRecord 从数据库加载模式一样。这已经是当前 Rails 样板文件的一部分了。


class PostsController < ApplicationController
  def new
    @post = Post.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml { render :xml => @post }
    end
  end
end

不过有一个问题,这可能不适用于受保护的或嵌套的操作。理想情况下,Rails 应用将为资源设置一个顶层路由,并在 request.format.xml? 为 true 时禁用任何 before 过滤器。


map.route 'tickets/new.:format', :controller => 'tickets', :action => 'new'

你可以通过直接修改 #schema 哈希,或调用 #reset_schema 并提供你自己的前缀来解决这个问题。这里有一个使用 Lighthouse API 库 的示例。


Lighthouse.account = 'entp'
Lighthouse.token = 'monkey'
Lighthouse::Ticket.reset_schema :project_id => 1

# or, use a well known public project
Lighthouse.account = 'rails'
Lighthouse::Ticket.reset_schema :project_id => 8994
Ticket.new # => #<Lighthouse::Ticket:0x1707898 @attributes={"permalink"=>nil, "updated_at"=>nil, "number"=>nil, "title"=>nil, "creator_id"=>nil, "tag"=>nil, "attachments_count"=>0, "priority"=>0, "closed"=>false, "assigned_user_id"=>nil, "user_id"=>nil, "created_at"=>nil, "state"=>nil, "milestone_id"=>nil}, @prefix_options={:project_id=>8994}>

评论?