Reputation:
I have a controller that responds_to html and png ( I load the image dynamically and render it as 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 )
I expected that this would work, but it stills tries to find a template file and ignores my method :(
models/user.rb
class User < ActiveRecord::Base
def to_png
File.read("some_file.png")
end
end
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
Upvotes: 0
Views: 2796
Reputation: 14943
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::Type.register "image/jpg", :jpg
http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
in 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
Upvotes: 1
Reputation: 3506
Try to add in file [YOUR_APP]/config/initializers/mime_types.rb
:
Mime::Type.register "image/png", :png
and restart your application
Upvotes: 2