在Rails 3中为VCF添加渲染器

Kyl*_*cot 1 ruby-on-rails ruby-on-rails-3

我正在尝试添加渲染器以允许我的某个模型响应.vcf格式.我已将以下代码添加到我的vcf_renderer.rb目录中的文件中initializers:

Mime::Type.register 'text/x-vcard', :vcf
ActionController::Renderers.add :vcf do |object, options|
  exit! # Testing to see if this even gets called at all...
end
Run Code Online (Sandbox Code Playgroud)

似乎以下代码永远不会被执行,因为如果我去/model/123.vcf我得到"模板丢失"错误.

有谁知道为什么ActionController::Renderers.add块似乎没有被调用?

AuthorsController.rb

respond_to :vcf

def show

  respond_with(@author)

end
Run Code Online (Sandbox Code Playgroud)

Tut*_*teC 6

看起来像旧样式工作,执行渲染器format.vcf { render :vcf => @object }.

使用respond_with(现在引发"缺失模板"),您必须在模型中添加to_vcf方法.试图show并且它有效(因为index它不能识别to_vcf数组).

# config/initializers/vcf_renderer.rb
Mime::Type.register 'text/x-vcard', :vcf
ActionController::Renderers.add :vcf do |object, options|
  self.content_type ||= 'text/x-vcard'
  self.response_body  = object.respond_to?(:to_vcf) ? object.to_vcf : object
end
Run Code Online (Sandbox Code Playgroud)