君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

Railsのrenderメソッドについて、xml, html, jsonで試してみる

htmlで返す

render html: 'content'
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def hello
    render html: '<ul><li>hello world</li><li>good bye world</li></ul>'
  end
end

ブラウザ上の表示

f:id:karoten512:20171012223709p:plain

あれ。うまく表示されない。

エスケープされてしまっている。

調べるとhtml_safeを用いればhtml要素がエスケープされないらしい。

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def hello
    render html: '<ul><li>hello world</li><li>good bye world</li></ul>'.html_safe
  end
end

うまくいった。

f:id:karoten512:20171012223825p:plain

レスポンスヘッダ

f:id:karoten512:20171012224230p:plain

MIMETYPEがtext/htmlになってる。

xmlで返す

render xml: 'content'
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def hello
    render xml: '<tag>hello world</tg>'
  end
end

ブラウザ上の表示

f:id:karoten512:20171012223415p:plain

レスポンスヘッダ

f:id:karoten512:20171012223429p:plain

jsonで返す

render json: 'content'
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def hello
    render json: '{"name": "carotene", "gender": "male"}'
  end
end

ブラウザ上の表示

f:id:karoten512:20171012224905p:plain

レスポンスヘッダ

f:id:karoten512:20171012224920p:plain

まとめ

xmlだったらRSS配信とかに使えるイメージ。

jsonは普通にapiかな。おそらくapiとして使う場合はjbuilder等のtemplateエンジンを使うみたい。