简体   繁体   English

Ruby on Rails response_with和图像格式

[英]Ruby on Rails respond_with and image formats

I have a controller that responds_to html and png ( I load the image dynamically and render it as text ). 我有一个控制器,它可以对HTML和png进行responses_to(我会动态加载图像并将其呈现为text)。 That makes the controller code messy and today I found respond_with, which looks very cool, but I can't found out how to make it work with formats, different than html, json and xml ( like the png ) 这使控制器代码变得混乱,今天我发现了respond_with,它看起来很酷,但是我不知道如何使它使用不同于html,json和xml(例如png)的格式

I expected that this would work, but it stills tries to find a template file and ignores my method :( 我期望这会起作用,但是它仍然尝试查找模板文件,并忽略了我的方法:(

models/user.rb 型号/user.rb

class User < ActiveRecord::Base  
  def to_png
    File.read("some_file.png")
  end
end

controllers/users_controller.rb controllers / users_controller.rb

class UsersController < ApplicationController
  respond_to :html, :png

  # GET /users/1
  def show
    @user = User.find(params[:id])
    respond_with(@user)
  end
end

Try to add in file [YOUR_APP]/config/initializers/mime_types.rb : 尝试添加文件[YOUR_APP]/config/initializers/mime_types.rb

Mime::Type.register "image/png", :png

and restart your application 并重新启动您的应用程序

if you need to use a MIME type which isn't supported by default, you can register your own handlers in environment.rb as follows. 如果您需要使用默认情况下不支持的MIME类型,则可以按照以下方法在environment.rb中注册自己的处理程序。

Mime::Type.register "image/jpg", :jpg

http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

in environment.rb 在environment.rb中

Mime::Type.register "image/png", :png

then 然后

respond_to do |format|
   format.png do
      #do stuff here
   end
end

or 要么

respond_with @user do |format|
   format.png do
      #do stuff here
   end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM