ݺߣ

ݺߣShare a Scribd company logo
Anton Shemerey
@shemerey
Single Responsibility Principle в Руби
и почему instance/class variables это ОЧЕНЬ пл
each object should have
one and
only one responsibility
Dear Anton Shemerey.
Thank you for your patronage. This letter is to confirm that your order from
Doe Books has been filled and should arrive within 15 days.
Shipping books at the book rate generally slows delivery. As you know, payment
in full ($20.75) is due by the end of the month.
Thank you for doing business with Doe. We look forward to serving you again.
If you have questions regarding the new pricing please contact support.
--
Sincerely yours, John Peter
Doe Books
720 S Michigan Ave
Chicago, IL, United States
+1 312-922-4400
Order Confirmation Page
Dear. Anton Shemerey
Thank you for your patronage. This letter is to confirm that your order from
Doe Books has been filled and should arrive within 15 days.
Shipping books at the book rate generally slows delivery. As you know, payment
in full ($20.75) is due by the end of the month.
Thank you for doing business with Doe Books. We look forward to serving you again.
If you have questions regarding the new pricing please contact support.
--
Sincerely yours, John Peter
Doe Books
720 S Michigan Ave
Chicago, IL, United States
+1 312-922-4400
Order Confirmation Page variables
Dear. {%user_full_name%}
Thank you for your patronage. This letter is to confirm that your order from
{%company_name%} has been filled and should arrive within {%delivery_time%}.
Shipping books at the book rate generally slows delivery. As you know, payment
in full ({%order_total%}) is due by the end of the month.
Thank you for doing business with {%company_name%}. We look forward to serving
you again. If you have questions regarding the {%price_url%} please
contact {%support_email%}.
--
Sincerely yours, {%owner_name%}
{%company_name%}
{%company_address%}
Order Confirmation Template
Data we have :(
• current_user.full_name #=> ‘Anton Shemerey’
• @order.estimated_delivery #=> ’15 days’
• @order.total #=> ‘<Money: @cents = 2075 ….’
• COMPANY_NAME #=> ‘Doe Books’
• $owner.full_name #=> ‘John Peter’
• @pricing_link #=> ‘http://example.com/price'
• $support_email = ‘support@example.com’
• @@company_address #=> ‘720 S Michigan Ave Chicago….’
Facepalm
Dear. <%= current_user.full_name %>
Thank you for your patronage. This letter is to confirm that your order from
<%= COMPANY_NAME %> has been filled and should arrive
within <%= @order.estimated_delivery%>.
Shipping books at the book rate generally slows delivery. As you know, payment
in full (<%= number_to_currency(@order.total) %>) is due by the end of the month.
Thank you for doing business with <%= COMPANY_NAME %>. We look forward to
serving you again. If you have questions regarding the <%= @pricing_link %> please
contact <%= email_to(“Support”, $support_email) %>.
--
Sincerely yours, <%= $owner.full_name %>
<%= COMPANY_NAME %>
<%= @@company_address %>
Order Confirmation Template
THE Controller :)
class OrdersController < ApplicationController
....
def confirmation
@order = Order.find(params[:id])
end
....
end
Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»
Dear. <%= current_user.full_name %>
Thank you for your patronage. This letter is to confirm that your order from
<%= COMPANY_NAME %> has been filled and should arrive
within <%= @order.estimated_delivery%>.
Shipping books at the book rate generally slows delivery. As you know, payment
in full (<%= number_to_currency(@order.total) %>) is due by the end of the month.
Thank you for doing business with <%= COMPANY_NAME %>. We look forward to
serving you again. If you have questions regarding the <%= @pricing_link %> please
contact <%= email_to(“Support”, $support_email) %>.
--
Sincerely yours, <%= $owner.full_name %>
<%= COMPANY_NAME %>
<%= @@company_address %>
Order Confirmation Template
Dear. <%= @current_user_full_name %>
Thank you for your patronage. This letter is to confirm that your order from
<%= @company_name %> has been filled and should arrive
within <%= @estimated_delivery_time %>.
Shipping books at the book rate generally slows delivery. As you know, payment
in full (<%= number_to_currency(@order_total) %>) is due by the end of the month.
Thank you for doing business with <%= @company_name %>. We look forward to
serving you again. If you have questions
regarding the <%= link_to(‘price’, @pricing_link) %> please
contact <%= email_to(“Support”, @support_email) %>.
--
Sincerely yours, <%= @owner_full_name %>
<%= @company_name %>
<%= @company_address %>
Order Confirmation Template Second Attempt
THE Controller :)
class OrdersController < ApplicationController
....
def confirmation
@order = Order.find(params[:id])
@current_user_full_name = current_user.full_name
@company_name = COMPANY_NAME
@estimated_delivery_time = @order.estimated_delivery
@order_total = @order.total
@pricing_link = 'http://example.com/price'
@support_email = 'support@example.com'
@owner_full_name = $owner.full_name
@company_address = @@company_address
end
....
end
Second Attempt
Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»
Dear. Anton Shemerey
Thank you for your patronage. This letter is to confirm that your order from
Doe Books has been filled and should arrive within 15 days.
Shipping books at the book rate generally slows delivery. As you know, payment
in full ($0) is due by the end of the month.
Thank you for doing business with Doe Books. We look forward to serving you
again. If you have questions regarding the new pricing please contact support.
--
Sincerely yours, John Peter
Doe Books
720 S Michigan Ave
Chicago, IL, United States
+1 312-922-4400
Free Order !!!!
Five sec to fix ;-)
class OrdersController < ApplicationController
# ....
def confirmation
@order = Order.find(params[:id])
@current_user_full_name = current_user.full_name
@company_name = COMPANY_NAME
@estimated_delivery_time = @order.estimated_delivery
@order_total = @order.total
@pricing_link = 'http://example.com/price'
@support_email = 'support@example.com'
@owner_full_name = $owner.full_name
@company_address = @@company_address
end
# ....
end
binding.pry
require 'pry'; binding.pry
2.0.0-p353 :006 > @order_total
=> #<Money:0x007fc7afb23530 @cents=83991, @currency="USD", @b
WTF ?!?!?!?!
Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»
Dear. <%= @current_user_full_name %>
Thank you for your patronage. This letter is to confirm that your order from
<%= @company_name %> has been filled and should arrive
within <%= @estimated_delivery_time %>.
Shipping books at the book rate generally slows delivery. As you know, payment
in full (<%= number_to_currency(@order_total) %>) is due by the end of the month.
Thank you for doing business with <%= @company_name %>. We look forward to
serving you again. If you have questions
regarding the <%= link_to(‘price’, @pricing_link) %> please
contact <%= email_to(“Support”, @support_email) %>.
--
Sincerely yours, <%= @owner_full_name %>
<%= @company_name %>
<%= @company_address %>
Order Confirmation Template binding.pry
<%- require 'pry'; binding.pry %>
2.0.0-p353 :0016 > @order_total
=> #<Money:0x007fc7afb23530 @cents=0, @currency="USD", @bank=#<M
WTF ?!?!?!?!
GREP!!!
$ grep -iRn @order_total app | wc
#=> 151 1017 17348
How are rails instance
variables passed to views
?????
AbstractController::Rendering#view_assigns
module AbstractController
module Rendering
# ....
# This method should return a hash with assigns.
# You can overwrite this configuration per controller.
# :api: public
def view_assigns
protected_vars = _protected_ivars
variables = instance_variables
variables.reject! { |s| protected_vars.include? s }
variables.each_with_object({}) { |name, hash|
hash[name.slice(1, name.length)] = instance_variable_get(name)
}
end
# ....
end
end
module AbstractController
def view_context
view_context_class.new(
view_renderer, view_assigns, self)
end
end
AbstractController#view_context
Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»
GREP!!!
$ grep -iRn @order_total app/helpers | wc
#=> 2 8 143
Second Attempt
module ApplicationHelper
....
def current_cart_total
if current_user
if order = current_user.current_order
@order_total = order.total
end
else
@order_total = Money.new(0)
end
end
....
end
$ git blame | grep current_cart_total
Problem Fixed!
class OrdersController < ApplicationController
before_action :load_order, only: [:show, :update, :destroy]
def update
if @order.update_attributes(params[:order])
redirect_to :show
else
render 'edit'
end
end
private
def load_order
@order = Order.find(params[:id])
end
end
Controller.before_action
class OrdersController < ApplicationController
....
def order
@order ||= Order.find(params[:id])
end
....
end
Memoization
class OrdersController < ApplicationController
helper_method :order
def update
if order.update_attributes(params[:order])
redirect_to :show
else
render 'edit'
end
end
private
def order
@_order ||= Order.find(params[:id])
end
end
Controller.helper_method
• memoization / lazy loading
• encapsulating (getter, setter)
• barewords (method, local variable,
helper_method, ….)
#source_location, caller
def total_order
stack = caller
require 'pry'; binding.pry
...
end
<% self.method(:total_order).source_location %>
one action one @
• PRESENTER
• SERVICE OBJECT
• PROXY OBJECT
• VALUE OBJECT
• LOCALS
• HELPER_METHOD
You can always use following
Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»
#destroy_all_view_assigns
group :development, :test do
gem 'destroy_all_view_assigns'
end
https://github.com/shemerey/destroy_all_view_assigns
https://github.com/shemerey
https://www.facebook.com/shemerey
https://twitter.com/shemerey
https://www.linkedin.com/in/shemerey
Questions ???

More Related Content

More from Olga Lavrentieva (20)

PPTX
15 10-22 altoros-fact_sheet_st_v4
Olga Lavrentieva
PPTX
Сергей Ковалёв (Altoros): Practical Steps to Improve Apache Hive Performance
Olga Lavrentieva
PPTX
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
Olga Lavrentieva
PDF
Владимир Иванов (Oracle): Java: прошлое и будущее
Olga Lavrentieva
PPTX
Brug - Web push notification
Olga Lavrentieva
PDF
Александр Ломов: "Reactjs + Haskell + Cloud Foundry = Love"
Olga Lavrentieva
PPTX
Максим Жилинский: "Контейнеры: под капотом"
Olga Lavrentieva
PPTX
Александр Протасеня: "PayPal. Различные способы интеграции"
Olga Lavrentieva
PPTX
Сергей Черничков: "Интеграция платежных систем в .Net приложения"
Olga Lavrentieva
PDF
Егор Воробьёв: «Ruby internals»
Olga Lavrentieva
PDF
Дмитрий Савицкий «Ruby Anti Magic Shield»
Olga Lavrentieva
PPTX
Сергей Алексеев «Парное программирование. Удаленно»
Olga Lavrentieva
PPTX
«Почему Spark отнюдь не так хорош»
Olga Lavrentieva
PPTX
«Cassandra data modeling – моделирование данных для NoSQL СУБД Cassandra»
Olga Lavrentieva
PPTX
«Практика построения высокодоступного решения на базе Cloud Foundry Paas»
Olga Lavrentieva
PPTX
«Дизайн продвинутых нереляционных схем для Big Data»
Olga Lavrentieva
PPTX
«Обзор возможностей Open cv»
Olga Lavrentieva
PPTX
«Нужно больше шин! Eventbus based framework vertx.io»
Olga Lavrentieva
PPTX
«Домовёнок кузя изгоняет лешего»
Olga Lavrentieva
PPTX
«Ruby integration testing tools»
Olga Lavrentieva
15 10-22 altoros-fact_sheet_st_v4
Olga Lavrentieva
Сергей Ковалёв (Altoros): Practical Steps to Improve Apache Hive Performance
Olga Lavrentieva
Андрей Козлов (Altoros): Оптимизация производительности Cassandra
Olga Lavrentieva
Владимир Иванов (Oracle): Java: прошлое и будущее
Olga Lavrentieva
Brug - Web push notification
Olga Lavrentieva
Александр Ломов: "Reactjs + Haskell + Cloud Foundry = Love"
Olga Lavrentieva
Максим Жилинский: "Контейнеры: под капотом"
Olga Lavrentieva
Александр Протасеня: "PayPal. Различные способы интеграции"
Olga Lavrentieva
Сергей Черничков: "Интеграция платежных систем в .Net приложения"
Olga Lavrentieva
Егор Воробьёв: «Ruby internals»
Olga Lavrentieva
Дмитрий Савицкий «Ruby Anti Magic Shield»
Olga Lavrentieva
Сергей Алексеев «Парное программирование. Удаленно»
Olga Lavrentieva
«Почему Spark отнюдь не так хорош»
Olga Lavrentieva
«Cassandra data modeling – моделирование данных для NoSQL СУБД Cassandra»
Olga Lavrentieva
«Практика построения высокодоступного решения на базе Cloud Foundry Paas»
Olga Lavrentieva
«Дизайн продвинутых нереляционных схем для Big Data»
Olga Lavrentieva
«Обзор возможностей Open cv»
Olga Lavrentieva
«Нужно больше шин! Eventbus based framework vertx.io»
Olga Lavrentieva
«Домовёнок кузя изгоняет лешего»
Olga Lavrentieva
«Ruby integration testing tools»
Olga Lavrentieva

Recently uploaded (20)

PPTX
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
PDF
Python Conference Singapore - 19 Jun 2025
ninefyi
PDF
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
PDF
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
PPTX
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
PDF
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
PDF
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
PDF
Open Source Milvus Vector Database v 2.6
Zilliz
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
Python Conference Singapore - 19 Jun 2025
ninefyi
ArcGIS Utility Network Migration - The Hunter Water Story
Safe Software
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
From Chatbot to Destroyer of Endpoints - Can ChatGPT Automate EDR Bypasses (1...
Priyanka Aash
Open Source Milvus Vector Database v 2.6
Zilliz
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
Why aren't you using FME Flow's CPU Time?
Safe Software
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
Ad

Антон Шемерей «Single responsibility principle в руби или почему instanceclass variables это очень плохо»

  • 1. Anton Shemerey @shemerey Single Responsibility Principle в Руби и почему instance/class variables это ОЧЕНЬ пл
  • 2. each object should have one and only one responsibility
  • 3. Dear Anton Shemerey. Thank you for your patronage. This letter is to confirm that your order from Doe Books has been filled and should arrive within 15 days. Shipping books at the book rate generally slows delivery. As you know, payment in full ($20.75) is due by the end of the month. Thank you for doing business with Doe. We look forward to serving you again. If you have questions regarding the new pricing please contact support. -- Sincerely yours, John Peter Doe Books 720 S Michigan Ave Chicago, IL, United States +1 312-922-4400 Order Confirmation Page
  • 4. Dear. Anton Shemerey Thank you for your patronage. This letter is to confirm that your order from Doe Books has been filled and should arrive within 15 days. Shipping books at the book rate generally slows delivery. As you know, payment in full ($20.75) is due by the end of the month. Thank you for doing business with Doe Books. We look forward to serving you again. If you have questions regarding the new pricing please contact support. -- Sincerely yours, John Peter Doe Books 720 S Michigan Ave Chicago, IL, United States +1 312-922-4400 Order Confirmation Page variables
  • 5. Dear. {%user_full_name%} Thank you for your patronage. This letter is to confirm that your order from {%company_name%} has been filled and should arrive within {%delivery_time%}. Shipping books at the book rate generally slows delivery. As you know, payment in full ({%order_total%}) is due by the end of the month. Thank you for doing business with {%company_name%}. We look forward to serving you again. If you have questions regarding the {%price_url%} please contact {%support_email%}. -- Sincerely yours, {%owner_name%} {%company_name%} {%company_address%} Order Confirmation Template
  • 6. Data we have :( • current_user.full_name #=> ‘Anton Shemerey’ • @order.estimated_delivery #=> ’15 days’ • @order.total #=> ‘<Money: @cents = 2075 ….’ • COMPANY_NAME #=> ‘Doe Books’ • $owner.full_name #=> ‘John Peter’ • @pricing_link #=> ‘http://example.com/price' • $support_email = ‘support@example.com’ • @@company_address #=> ‘720 S Michigan Ave Chicago….’
  • 8. Dear. <%= current_user.full_name %> Thank you for your patronage. This letter is to confirm that your order from <%= COMPANY_NAME %> has been filled and should arrive within <%= @order.estimated_delivery%>. Shipping books at the book rate generally slows delivery. As you know, payment in full (<%= number_to_currency(@order.total) %>) is due by the end of the month. Thank you for doing business with <%= COMPANY_NAME %>. We look forward to serving you again. If you have questions regarding the <%= @pricing_link %> please contact <%= email_to(“Support”, $support_email) %>. -- Sincerely yours, <%= $owner.full_name %> <%= COMPANY_NAME %> <%= @@company_address %> Order Confirmation Template
  • 9. THE Controller :) class OrdersController < ApplicationController .... def confirmation @order = Order.find(params[:id]) end .... end
  • 11. Dear. <%= current_user.full_name %> Thank you for your patronage. This letter is to confirm that your order from <%= COMPANY_NAME %> has been filled and should arrive within <%= @order.estimated_delivery%>. Shipping books at the book rate generally slows delivery. As you know, payment in full (<%= number_to_currency(@order.total) %>) is due by the end of the month. Thank you for doing business with <%= COMPANY_NAME %>. We look forward to serving you again. If you have questions regarding the <%= @pricing_link %> please contact <%= email_to(“Support”, $support_email) %>. -- Sincerely yours, <%= $owner.full_name %> <%= COMPANY_NAME %> <%= @@company_address %> Order Confirmation Template
  • 12. Dear. <%= @current_user_full_name %> Thank you for your patronage. This letter is to confirm that your order from <%= @company_name %> has been filled and should arrive within <%= @estimated_delivery_time %>. Shipping books at the book rate generally slows delivery. As you know, payment in full (<%= number_to_currency(@order_total) %>) is due by the end of the month. Thank you for doing business with <%= @company_name %>. We look forward to serving you again. If you have questions regarding the <%= link_to(‘price’, @pricing_link) %> please contact <%= email_to(“Support”, @support_email) %>. -- Sincerely yours, <%= @owner_full_name %> <%= @company_name %> <%= @company_address %> Order Confirmation Template Second Attempt
  • 13. THE Controller :) class OrdersController < ApplicationController .... def confirmation @order = Order.find(params[:id]) @current_user_full_name = current_user.full_name @company_name = COMPANY_NAME @estimated_delivery_time = @order.estimated_delivery @order_total = @order.total @pricing_link = 'http://example.com/price' @support_email = 'support@example.com' @owner_full_name = $owner.full_name @company_address = @@company_address end .... end Second Attempt
  • 15. Dear. Anton Shemerey Thank you for your patronage. This letter is to confirm that your order from Doe Books has been filled and should arrive within 15 days. Shipping books at the book rate generally slows delivery. As you know, payment in full ($0) is due by the end of the month. Thank you for doing business with Doe Books. We look forward to serving you again. If you have questions regarding the new pricing please contact support. -- Sincerely yours, John Peter Doe Books 720 S Michigan Ave Chicago, IL, United States +1 312-922-4400 Free Order !!!!
  • 16. Five sec to fix ;-)
  • 17. class OrdersController < ApplicationController # .... def confirmation @order = Order.find(params[:id]) @current_user_full_name = current_user.full_name @company_name = COMPANY_NAME @estimated_delivery_time = @order.estimated_delivery @order_total = @order.total @pricing_link = 'http://example.com/price' @support_email = 'support@example.com' @owner_full_name = $owner.full_name @company_address = @@company_address end # .... end binding.pry require 'pry'; binding.pry
  • 18. 2.0.0-p353 :006 > @order_total => #<Money:0x007fc7afb23530 @cents=83991, @currency="USD", @b WTF ?!?!?!?!
  • 20. Dear. <%= @current_user_full_name %> Thank you for your patronage. This letter is to confirm that your order from <%= @company_name %> has been filled and should arrive within <%= @estimated_delivery_time %>. Shipping books at the book rate generally slows delivery. As you know, payment in full (<%= number_to_currency(@order_total) %>) is due by the end of the month. Thank you for doing business with <%= @company_name %>. We look forward to serving you again. If you have questions regarding the <%= link_to(‘price’, @pricing_link) %> please contact <%= email_to(“Support”, @support_email) %>. -- Sincerely yours, <%= @owner_full_name %> <%= @company_name %> <%= @company_address %> Order Confirmation Template binding.pry <%- require 'pry'; binding.pry %>
  • 21. 2.0.0-p353 :0016 > @order_total => #<Money:0x007fc7afb23530 @cents=0, @currency="USD", @bank=#<M WTF ?!?!?!?!
  • 22. GREP!!! $ grep -iRn @order_total app | wc #=> 151 1017 17348
  • 23. How are rails instance variables passed to views ?????
  • 24. AbstractController::Rendering#view_assigns module AbstractController module Rendering # .... # This method should return a hash with assigns. # You can overwrite this configuration per controller. # :api: public def view_assigns protected_vars = _protected_ivars variables = instance_variables variables.reject! { |s| protected_vars.include? s } variables.each_with_object({}) { |name, hash| hash[name.slice(1, name.length)] = instance_variable_get(name) } end # .... end end
  • 25. module AbstractController def view_context view_context_class.new( view_renderer, view_assigns, self) end end AbstractController#view_context
  • 27. GREP!!! $ grep -iRn @order_total app/helpers | wc #=> 2 8 143 Second Attempt module ApplicationHelper .... def current_cart_total if current_user if order = current_user.current_order @order_total = order.total end else @order_total = Money.new(0) end end .... end
  • 28. $ git blame | grep current_cart_total Problem Fixed!
  • 29. class OrdersController < ApplicationController before_action :load_order, only: [:show, :update, :destroy] def update if @order.update_attributes(params[:order]) redirect_to :show else render 'edit' end end private def load_order @order = Order.find(params[:id]) end end Controller.before_action
  • 30. class OrdersController < ApplicationController .... def order @order ||= Order.find(params[:id]) end .... end Memoization
  • 31. class OrdersController < ApplicationController helper_method :order def update if order.update_attributes(params[:order]) redirect_to :show else render 'edit' end end private def order @_order ||= Order.find(params[:id]) end end Controller.helper_method
  • 32. • memoization / lazy loading • encapsulating (getter, setter) • barewords (method, local variable, helper_method, ….)
  • 33. #source_location, caller def total_order stack = caller require 'pry'; binding.pry ... end <% self.method(:total_order).source_location %>
  • 34. one action one @ • PRESENTER • SERVICE OBJECT • PROXY OBJECT • VALUE OBJECT • LOCALS • HELPER_METHOD You can always use following
  • 36. #destroy_all_view_assigns group :development, :test do gem 'destroy_all_view_assigns' end