5.1.1partial去除重复

代码的第一坏味道:重复

原版的app/views/movies/new.html.haml,

%h2 Create New Movie

= form_tag movies_path, :method => :post do

  = label :movie, :title, 'Title'
  = text_field :movie, :title

  = label :movie, :rating, 'Rating'
  = select :movie, :rating, ['G','PG','PG-13','R','NC-17']
 
  = label :movie, :release_date, 'Released On'
  = date_select :movie, :release_date

  = submit_tag 'Save Changes'

原版的app/views/movies/edit.html.haml

%h2 Edit Movie

= form_tag movie_path(@movie), :method => :put do

  = label :movie, :title, 'Title'
  = text_field :movie, :title

  = label :movie, :rating, 'Rating'
  = select :movie, :rating, ['G','PG','PG-13','R','NC-17']
 
  = label :movie, :release_date, 'Released On'
  = date_select :movie, :release_date

  = submit_tag 'Save Changes'

修改app/models/movie.rb,将评级的可选项作为movie模型类的属性

class Movie < ActiveRecord::Base
  def self.all_ratings; %w[ G PG PG-13 R NC-17] ; end
end

将上面new.html.haml和edit.html.haml的公共部分提取出来,提取到文件app/views/movies/_movie_form.html.haml,注意去掉缩进

= label :movie, :title, 'Title'
= text_field :movie, :title

= label :movie, :rating, 'Rating'
= select :movie, :rating, Movie.all_ratings

= label :movie, :release_date, 'Released On'
= date_select :movie, :release_date

修改后新版的app/views/movies/new.html.haml,

-# new.html.haml using partial

%h2 Create New Movie

= form_tag '/movies', :method => :post do
  = render :partial => 'movie_form'
  = submit_tag 'Save Changes'

原版的app/views/movies/edit.html.haml

-# edit.html.haml using partial

%h2 Edit Existing Movie

= form_tag movie_path(@movie), :method => :put do
  = render :partial => 'movie_form'
  = submit_tag 'Update Movie Info'

5.1.2把单行电影显示定义为partial

添加app/views/movies/_movie.html.haml

-# A single row of the All Movies table
%tr
  %td= movie.title 
  %td= movie.rating
  %td= movie.release_date
  %td= link_to "More about #{movie.title}", movie_path(movie)

原版的app/views/movies/index.html.haml

-#  This file is app/views/movies/index.html.haml
%h1 All Movies

%table#movies
  %thead
    %tr
      %th Movie Title
      %th Rating
      %th Release Date
      %th More Info
  %tbody
    - @movies.each do |movie|
      %tr
        %td= movie.title
        %td= movie.rating
        %td= movie.release_date
        %td= link_to "More about #{movie.title}", movie_path(movie)
-# add to end of index.html.haml
= link_to 'Add new movie', new_movie_path

可修改为