over 10 years ago

基本用法

不需要傳參數的狀況

不需要傳參數進 cells

<%= render_cell :statics, :today %>
class StaticsCell < Cell::Rails
  def today
    ....
    render
  end
end
  • 如果不需要參數,那麼就跟一般 ruby method 一樣
注意
  • 如果這個 method 需要 render view ( 90% 的狀況需要),method 最後一定要加 render。很多開發者 debug 到死就是因為不知道要加 render

  • 換句話說,如果沒加 render,其實可以拿來吐 cached 過的 pure result,如 ArrayString...etc.

需要傳參數的狀況

在上一篇文章,我們需要傳一個 user 進去撈資料。那麼 View 是這樣寫的

app/views/users/show.html.erb
   <%= render_cell :user, :rencent_posts, :user => :user %>

如果需要傳多個以上的參數,後面繼續加就可以了。

   <%= render_cell :auction, :daily_data, :user => :user, :date => Date.today %>

在 Cells 裡面收資料,使用第一個 argument 收進來。

class AuctionCell < Cell::Rails
  def daily_data(args)
    @user = args[:user]
    @date = args[:date]
    render
  end
end

打 Cache

在一般的狀況下,使用 Cells 是「沒有 cache」的,也就是普通的 View component 而已。要有 cache 效果必須特別指定...

指定時間

class UserCell < Cell::Rails

 cache :recent_posts, :expires_in => 1.hours

  def recent_posts(args)
    ...
  end
  
end

指定條件 cache

有時候,開發者希望該個元件除了一個小時 Cache 之外,還希望這個物品一旦內容被更新時,不要管一個小時原則,立刻更新。那麼可以用這樣的方式更新。

class ProductCell < Cell::Rails
  cache :product, :expires_in => 1.hours do |cell, item|
    "#{item[:product].id}-#{item[:product].updated_at}"
  end
  
  def info(args)
    @product = args[:product]
    render
  end
end  

使用 Helper

在 cells 時,是無法用 Rails 裡面的 helper 的,所以會出現 method undefined,必須在 cells 手動宣告。

class ProductCell < Cell::Rails

  helper ProductsHelper
 
  def info(args)
    @product = args[:product]
    render
  end
end  

使用 Cells 外的 partial

在 Cells 時,也是無法用 Rails 內的 partial,必須手定指定

class ProductCell < Cell::Rails
  append_view_path("app/views")
 
  def info(args)
    @product = args[:product]
    render
  end
end  

使用 current_user

有時候想偷懶,在 Cells 時直接呼叫 devise 裡面提供的 current_user,而非傳一個 user 參數進來。(我很不建議直接使用 current_user ...)

不過這也是可以做到的。在 Cells 裡面宣告 helper_method 就可以了。

class UserCell < Cell::Rails
  include Devise::Controllers::Helpers
  helper_method :current_user
   
  def recent_posts(args)
    ...
  end
end


這篇就大概 cover 使用 Cells 95% 上會遇到的狀況了。

後面幾個用法是 undocumentd features,解法當初是在 issue list 上或是 source code 撈到的...

小結

雖然現在已經有 Cache Digest 了,但我本身還是偏好使用 cells。理由當然是不外乎 cells 還是可以解決不少封裝的問題,而不只是當作 cachable partial ....

如果你在專案中常遇到 View 有複雜難以整理的問題,我相當推薦使用 cells

另外作者 Nick,在 Twitter 上有帳號 apotonick,歡迎 follow 他。

兩年前 (2011) 他也有來台灣參加過 RubyConf Taiwan,當時是借住在我租的公寓....XD。

系列連結:

← Cells 實作 Partial 封裝的最佳實踐 (2) 一趟 MVP 的旅程:在 Logdown 學到的幾件事 →
 
comments powered by Disqus