SlideShare a Scribd company logo
1 of 37
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
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
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 ?!?!?!?!
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
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
#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

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

More from Olga Lavrentieva (20)

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

Recently uploaded

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Антон Шемерей «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
  • 10.
  • 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
  • 14.
  • 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 ?!?!?!?!
  • 19.
  • 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
  • 26.
  • 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
  • 35.
  • 36. #destroy_all_view_assigns group :development, :test do gem 'destroy_all_view_assigns' end