うちのいぬ Tech Blog

Tech Blog of Uchinoinu/My dog

Crafting Rails 4 Applications - capter 1-4 - Talking It to the Next Level

こちらの記事の続きです。

tsumekoara.hateblo.jp

f:id:susanne:20150407133905j:plain

1.4 次のレベルへ

rendererの実装に話を戻します。以下の様なcontrollerでないが起きるか勉強してきました。

format.pdf { render pdf: "contents" }

実装中のrendererでは、以下の様になります。

pdf = Prawn::Document.new
pdf.text render_to_string( {} )
send_data( pdf.render, filename: "contents.pdf",
  disposition: "attachment" )

render_to_string()を空ハッシュと呼び出したとき、_normalize_options()メソッドはからハッシュを検知し、テンプレートを現在のアクションの名前に変換してレンダリングします。最後に、render_to_string( {} )は "#{controller_name}/#{action_name}" をview-rendererオブジェクトに渡します。

rendererがrender_to_string()に依存していることにより、以下のオプションが使えるようになります。

render pdf: "contents", template: "path/to/template"

内部では、以下のコードと同様になります。

pdf = Prawn::Document.new
pdf.text render_to_string(template: "path/to/template")
send_data( pdf.render, filename: "contens.pdf",
  disposition: "attachment" )

今回はrender_to_string()がレンダリングするTemplateを受け取ります。PDF rendererを終了させるには、選ばれたテンプレートがレンダリングされたことを確認するテストを追加します。:pdf, :templateオプションの両方でrender()を呼び出すHomeControllerでの新しいアクションを呼びだすテストです。

pdf_renderer/2_final/test/dummy/app/controllers/home_controller.rb

def another
  render pdf: "contents", template: "home/index"
end

このアクション用の新しいルーティングを追加します。

pdf_renderer/2_final/test/dummy/config/routes.rb

get "/another", to: "home#another", as: :another

/another.pdfにアクセスしPDFが返されることをテストします。

pdf_renderer/2_final/test/integration/pdf_delivery_test.rb

test "pdf renderer users the specified template" do
  get another_path(format: :pdf)
  assert_match "PDF", response.body
  assert_equal "binary", headers["Content-Transfer-Encodeing"]
  assert_equal "attachment; filename=\"contents.pdf\"",
    headers["Content-Disposition"]
  assert_equal "application/pdf", headers["Content-Type"]
end

テストを走らせて、動作を確認しましょう。

Work In Progress

1-1. Crafting Rails 4 Applications - capter 1-1 - Satomi's Daily Notes

1-2. Crafting Rails 4 Applications - capter 1-2 - Writing the Renderer - Satomi's Daily Notes

1-3. Crafting Rails 4 Applications - capter 1-3 - Understanding the Rails Rendering Stack - Satomi's Daily Notes