2. Problématique
Comment partager un widget entre les pages du site ?
github: apotonick/cells
3. Solution à l’ancienne
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :set_shopping_cart
private
def set_shopping_cart
@shopping_cart = ShoppingCart.for_user(current_user)
end
end
# app/views/layouts/application.html.erb
<%= render 'shared/shopping_cart', shopping_cart: @shopping_cart %>
# app/views/shared/_shopping_cart.html.erb
<% if @shopping_cart %>
# shopping cart rendering
<% end %>
github: apotonick/cells
4. Solution avec Cells
# app/views/layouts/application.html.erb
<%= render_cell :shopping_cart, :display, user: current_user %>
# app/cells/shopping_cart_cell.rb
class ShoppingCartCell < Cell::Rails
def display(opts)
@shopping_cart = ShoppingCart.for_user(opts[:user])
render
end
end
# app/cells/shopping_cart/display.html.erb
<% if @shopping_cart %>
# shopping cart rendering
<% end %>
github: apotonick/cells
5. Avantages
Séparation des responsabilités
Meilleure organisation du code
app/
cells/
shopping_cart/
display.html.erb
shopping_cart.rb
github: apotonick/cells
6. Aller plus loin - actions
# app/cells/shopping_cart_cell.rb
class ShoppingCartCell < Cell::Rails
def display(opts)
@shopping_cart = ShoppingCart.for_user(opts[:user])
render
end
def count(opts)
shopping_cart = ShoppingCart.for_user(opts[:user])
@items_count = shopping_cart.items_count
render
end
end
# app/views/layouts/application.html.erb
<%= render_cell :shopping_cart, :display, user: current_user %>
<%= render_cell :shopping_cart, :count, user: current_user %>
github: apotonick/cells
7. Aller plus loin - cache
# app/cells/shopping_cart_cell.rb
class ShoppingCartCell < Cell::Rails
cache :display, expires_in: 10.minutes
def display(opts)
# ...
end
end
github: apotonick/cells
8. Aller plus loin - cache
# app/cells/shopping_cart_cell.rb
class ShoppingCartCell < Cell::Rails
cache :display do |cell, opts|
opts[:user]
end
def display(opts)
# ...
end
end
github: apotonick/cells
9. Aller plus loin - helpers
# app/cells/shopping_cart_cell.rb
class ShoppingCartCell < Cell::Rails
helper MyAwesomeHelper
def display(opts)
@shopping_cart = ShoppingCart.for_user(opts[:user])
render
end
end
# app/cells/shopping_cart/display.html.erb
<%= do_something_awesome %>
github: apotonick/cells