將簡單的介紹 Ruby 的基礎語法,用意是之後在閱讀或撰寫 Rails 專案的時候,會比較知道 Rails 在寫些什麼。
變數種類:
有效範圍:
要注意全域變數的使用 (本專案目前沒有用到),一但使用了,任何地方都可以使用,在撰寫 Rails 專案時,如果使用的不好,會給其他同事造成困擾。區域變數來講的話,相對就是區域一點 (也就是具有一定的範圍),這在 Rails 專案很常使用。
def update_cartons_quantity
  return if record.fd?
  context = HAWB::CartonsQuantityCalculator.new(hawb_record: record)
  record.update(cartons_quantity: context.result) if context.perform
end
定義在 update_cartons_quantity 方法裡的 context 變數,在離開 update_cartons_quantity 方法就失效了。
流程控制:
if..else.. 如果不然就:
if context.perform
  flash[:success] = 'Successfully approved'
else
  flash[:error] = context.errors.full_messages.to_sentence
end
if..elsif..else.. 如果..或是如果這樣..不然就:
if exporter? || export_supervisor?
  'EX'
elsif importer?
  'IM'
else
  query_params[:department]
end
在 Rails 的世界裡,要注意使用的是 elsif 而不是 else if.
unless 如果不是:
unless flash[:notice].blank? && flash[:error].blank?
  flash[:success] = I18n.t('successes.messages.update.success_update')
end
使用 unless,要避免 unless 後面的判斷式是 !.... (否定..),就會造成很繞舌,造成閱讀及日後理解的不便。
case..when..用法:
case region.to_sym
when :APAC
    apac_rules
when :AMER
    amer_rules
else
    false
end
把 if 放到後面去:
if context.perform
  record.update(cartons_quantity: context.result)
end
像這個 if 區塊只有一行程式碼,就可以改成如下:
record.update(cartons_quantity: context.result) if context.perform
迴圈:
介紹此專案很常使用到的 each 方法。
<tbody>
  <% @records.each do |record| %>
    <% hawb_record = record.hawb_record %>
    <tr class="text-center">
      <td><%= link_to hawb_record.number, edit_brokerage_path(params[:customer], record), target: :_blank %></td>
      <td><%= hawb_record.last_routing&.mawb_number %></td>
      <td><%= hawb_record.origin_port %></td>
      <td><%= hawb_record.destination_port %></td>
      <td><%= hawb_record.vplant&.number %></td>
      <td><%= t record.broker_return %></td>
      <td><%= record.department %></td>
      <td><%= time_as record.submission_at, :year_day %></td>
    </tr>
  <% end %>
</tbody>
這就是使用了 each 方法,一個一個的把資料轉出來印在畫面上。