Custom formats in Ruby on Rails - ruby-on-rails

I'm creating a website in Ruby on Rails, where users can login using RESTful Authentication. Someone can get a specific user using html, xml and json, just like scaffolding. But I want to add one more format: vCard (e.g. /users/1.vcard). This has a specific format, but how do I define my own formats? Using views, or must I use another way? Thanks

In your /config/initializers/mime_types.rb file, add a new registration for your format. It should look something like this:
Mime::Type.register "text/x-vcard", :vcard #The :vcard is the important part
After that (you'll have to restart your app to pick up the change), you can respond to the symbol like any other format:
# then in your controller action
def show
respond_to do |format|
format.html # render html
format.vcard { #render vcard }
end
end
Adding from comments (thanks nanda):
In your views folder, then, you would put the vCard template into a show.vcard.erb file (for example).

Related

Generate XML file and redirect to other view with Rails

I have a piece of code that generates an XML file. What I want to, and didn't find the solution, is to generate the XML file and ALSO redirect to another page, to give a feedback message.
My code is
def exportFiles
#files=FileToExport.getComponentToExport
recursive_tree= GitHubRepositorioService.getRecursiveTree('master')
GitHubService.updateFiles(#files, recursive_tree)
xml = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
respond_to do |format|
format.xml { send_data render_to_string(:exportFiles), filename: 'exported_module.xml', type: 'application/xml', disposition: 'attachment' }
end
FileToExport.setComponentToExport(nil)
end
As I already use "respond_to" I can't use another redirect sentence... so, there is a way to generate (downloading) that file and redirect to other view?
Unfortunately, this is not possible via the controller as you can't send two responses.
But you could do this via javascript for instance. See this topic for more info Rails how do I - export data with send_data then redirect_to a new page?

ruby code is showing as html in template

I have a rails app which uses angularjs. Here I'm trying to render a template from rails controller and pass a resource to the template. But the ruby code for displaying the variables are showing exactly as it is in the html.erb view.
def fail
#order = Order.find(1)
render 'payments/fail'
end
in view
<%= #order.as_json %>
My guess would be that the problem is in the name of your view file. I'd guess that you named it something like fail.html instead of fail.html.erb. Without the .erb suffix, Rails just interprets the file as html text and renders it without interpreting the ruby code.
However, changing the file name isn't quite the correct solution. Since you want to render json instead of HTML you don't need to create a view template, so you should just delete the template file altogether.
All Rails models have an .as_json method automatically, so you can simply modify your controller's fail method like so:
def fail
#order = Order.find(1)
render json: #order.as_json
end
Also if you want to do something fancy and modify the json that is returned, you can define your own as_json method inside the model.

locate file loaded on respond_with #jobs

On my project I have
respond_to :json
load_and_authorize_resource
def show
respond_with #job_pattern
end
as per tutorial here http://blog.plataformatec.com.br/2009/08/embracing-rest-with-mind-body-and-soul/
it works like this: when a request comes, for example with format xml, it will first search for a template at users/index.xml
so I checked for job_patterns/index.json but didnt find any file with this name
can anyone guide me where i can find the file or how the output is generated here if it is not with the file.
Because respond_to :json does not render a view, rather it calls render json: #job_pattern.
render json:#job_pattern calls #job_pattern.to_json and sets the JSON string as the response body. You can do the same with XML or YML.
This is an example of the rails convention over configuration philosophy - if there is a show.json.[erb|haml] it takes priority. Otherwise rails will look for an instance variable which corresponds with the name of the controller (#job or #jobs for index) and attempt to serialize it as JSON.
Further reading:
Justin Weiss: respond_to Without All the Pain
Rails Guides: Layouts and Rendering in Rails
In your case, your action is show so the template associated with is show.json in views/[namespace]/show.json.
You should create this template, or if this template is not found Rails will automatically invoke to_json on the object passed to respond_with.
Refer to documentation.
Recents version of Rails with generated scaffold use show.json.jbuilder as template file.
For more info about it:
jbuilder

Rails 3 render plaintext page using view

I have a Linux configuration file stored in my database in Rails, and I'd like to be able to download the configuration through a web request
My goal on the Linux side is to curl/wget the webpage, compare it to the current configuration, and then hup the server. Easy enough to do in a script.
In normal circumstances on Rails, you could do
render :text => #config_file
However, I need to do some formatting of the data first to apply the static headers, etc. This isn't a one-liner, so I need to be able to render a view.
I have the following set in my controller, but I still get a minimal set of HTML tags in the document
render(:content_type => 'text/plain', :layout => false);
I've done something similar in .Net before, so it printed out a text file with \n interpreted. How do I get that in Rails?
Normally, this is done with
# config/initializers/mime_types.rb
# ...
# Mime::Type.register "text/plain", :plaintext
# No changes needed as rails comes preconfigured with the text/plain mime type
# app/controllers/my_controller.rb
class MyController < ApplicationController
def my_action
respond_to do |format|
format.text
end
end
end
and a view file
# app/views/my_controller/my_action.text.erb
...
About the minimal HTML you find in the DOM: Are you seeing this from within some kind of in-browser inspector, like the ones included in google chrome or safari? If so then don't worry, this is added by the browser in order to display your text/plain document inline. If you look at the source of the delivered document (ctrl-u) no HTML should show up.

Rails: Easiest way to provide file downloads?

G'day guys, currently have almost finished writing a rails application that allows a CSV download of the database. This is generated when the index is first viewed.
Is there an easy way to insert a link to a helper that returns a CSV document? That is to say is it easy to insert links to helpers? This would make a lot of problems I've been having much easier
If you sticked to the general conventions, then you registered a mime-type for csv and return the csv file content via your #index action. So your link helper would be like this:
link_to 'export as csv', posts_path(:format => :csv)
If, in exchange, your file is generated WHEN index is first view but NOT BY Rails, you may want to avoid standart render and call send_data or send_file instead (check the api for them).
# in your controller:
def index
# your suff here
#csv_path = find_or_generate_csv_file
send_data #csv_path, :type=>"text/csv", :disposition=>'attachment'
end
protected
def find_or_generate_csv_file
#your file generation logic
end

Resources