Note that there are some explanatory texts on larger screens.

plurals
  1. POrespond_to with custom format aliasing json format, is this possible?
    text
    copied!<p>I have a situation where I'm returning json objects to my application which are built from YML files. Because to parse the yml file and return it as json I always have to do something like this:</p> <pre><code>format.json { render json: YAML.load(render_to_string :file =&gt; File.join(Rails.root,'app','views','home','icons.yml.erb'), :layout =&gt; false ) } </code></pre> <p>I would like to make this operation shorter, by creating a custom format that (however) result in a json, so I don't want to create a new mime type.</p> <p>My idea is to write:</p> <pre><code>format.myformat </code></pre> <p>Which will automatically search for <em>myaction.myformat.erb</em> inside views/mycontroller directory, and will automatically parse the yaml file returning it as a json object.</p> <p>Is this possible? If yes, how can I eventually do this?</p> <p><strong>Edit 1:</strong> I found an important suggestion in config/mime_types.rb:</p> <pre><code>Mime::Type.register_alias "text/html", :iphone </code></pre> <p>So I <strong>can</strong> alias a mime type, now the biggest problem is: how to define the default render action for a given format, like format.html does?</p> <p>If I write</p> <pre><code>format.html </code></pre> <p>current_action.html.erb will be automatically rendered, how can I choose the correct method to render a custom format?</p> <p><strong>Edit 2:</strong></p> <p>I managed to create this code (inside a controller, through some helper methods I built):</p> <pre><code> def icons respond_to do |format| format.extjson { render_to_extjson } end end </code></pre> <p>Is possible to make rails understand that if I write:</p> <pre><code> def icons respond_to do |format| format.extjson end end </code></pre> <p>it has to do:</p> <pre><code>format.extjson { render_to_extjson } </code></pre> <p>by default?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload