The document provides tips for improving performance in a Ruby on Rails application. It discusses using replication and read-only databases for certain queries and background jobs to improve performance. It also provides examples of preloading association data, using aggregation in SQL queries instead of separate queries, adding indexes, and implementing caching to reduce the number of database queries.
How to improve performance testing of your application? The best way is to include performance test into your CI pipeline! Based on the examples from GOG Store, let's check how to integrate Blackfire Player with Docker and Continuous Integration pipelines!
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
Slides from my talk at Symfony UK Meetup. London, 20 Aug 2014. http://twitter.com/cakper
Video: https://www.youtube.com/watch?v=cha92Og9M5A
More Domain-Driven Design related content at: https://domaincentric.net/
A helper to make the life of Wordpress developers easier.
This helper can be used to quickly register Custom Post Types, Taxonomies, Meta Boxes, Menu Pages and Sidebars within your Wordpress projects. Please comment, review, watch, fork and report bugs.
How to improve performance testing of your application? The best way is to include performance test into your CI pipeline! Based on the examples from GOG Store, let's check how to integrate Blackfire Player with Docker and Continuous Integration pipelines!
Scaling Symfony2 apps with RabbitMQ - Symfony UK MeetupKacper Gunia
Slides from my talk at Symfony UK Meetup. London, 20 Aug 2014. http://twitter.com/cakper
Video: https://www.youtube.com/watch?v=cha92Og9M5A
More Domain-Driven Design related content at: https://domaincentric.net/
A helper to make the life of Wordpress developers easier.
This helper can be used to quickly register Custom Post Types, Taxonomies, Meta Boxes, Menu Pages and Sidebars within your Wordpress projects. Please comment, review, watch, fork and report bugs.
Presented by Gregg Donovan, Senior Software Engineer, Etsy.com, Inc.
Understanding the impact of garbage collection, both at a single node and a cluster level, is key to developing high-performance, high-availability Solr and Lucene applications. After a brief overview of garbage collection theory, we will review the design and use of the various collectors in the JVM.
At a single-node level, we will explore GC monitoring -- how to understand GC logs, how to monitor what % of your Solr request time is spend on GC, how to use VisualGC, YourKit, and other tools, and what to log and monitor. We will review GC tuning and how to measure success.
At a cluster-level, we will review how to design for partial availability -- how to avoid sending requests to a GCing node and how to be resilient to mid-request GC pauses.For application development, we will review common memory leak scenarios in custom Solr and Lucene application code and how to detect them.
Una panoramica su Net::Amazon::EC2 e Net::RackSpace::Servers. Potete trovare la presentazione con le note qui: http://polettix.s3.amazonaws.com/IPW2011/nubilus-perl-1.1-note.pdf
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from? At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
As presented at Dutch PHP Conference 2015, an introduction to command buses, how to implement your own in PHP and why they're both useful but unimportant.
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
What makes your code slow? How do you make it faster? And how do you prove it?
This talk will describe my adventures benchmarking and optimizing ordered hashes in Perl, culminating in the release of Hash::Ordered (http://p3rl.org/Hash::Ordered) — which outperforms all other CPAN alternatives, often by a substantial margin. We will cover:
* How to customize Benchmark.pm
* How and why to benchmark at different scales
* Why tied anything in Perl is a horrible idea
* How ordered hashes got faster from a simple algorithm change
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
Polo: Desenvolvendo os problemas de inconsistência de dados em projetos Railstdc-globalcode
Sabe aquele bug que só acontece em produção? Aquela tela que renderiza um pouco diferente porque tem aqueles dados diferentes que só existem no banco de dados de prod? Ou aquele usuário maluco que causou todos aqueles corner cases porque o input dele era muito diferente? Todo mundo já passou por esses problemas! E por que essas coisas acontecem? Uma das respostas é fácil: faltaram dados. Depois de muita dor de cabeça brigando com rake db:seeds, db:migrations, muito SQL e de abrir muito rails console em produção que eu resolvi que era hora de resolver esse problema de uma maneira diferente. Foi aí que eu criei o Polo. Uma ruby gem que automatiza a criação de dumps do seu banco de dados em produção e gera amostras pra você poder importar no seu ambiente de desenvolvimento. Não perca mais tempo quebrando a cabeça com dados inconsistentes, fazendo deploys para produção só pra testar um corner case, ou abrindo console do rails em produção e brincando com a morte.
Presented by Gregg Donovan, Senior Software Engineer, Etsy.com, Inc.
Understanding the impact of garbage collection, both at a single node and a cluster level, is key to developing high-performance, high-availability Solr and Lucene applications. After a brief overview of garbage collection theory, we will review the design and use of the various collectors in the JVM.
At a single-node level, we will explore GC monitoring -- how to understand GC logs, how to monitor what % of your Solr request time is spend on GC, how to use VisualGC, YourKit, and other tools, and what to log and monitor. We will review GC tuning and how to measure success.
At a cluster-level, we will review how to design for partial availability -- how to avoid sending requests to a GCing node and how to be resilient to mid-request GC pauses.For application development, we will review common memory leak scenarios in custom Solr and Lucene application code and how to detect them.
Una panoramica su Net::Amazon::EC2 e Net::RackSpace::Servers. Potete trovare la presentazione con le note qui: http://polettix.s3.amazonaws.com/IPW2011/nubilus-perl-1.1-note.pdf
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from? At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
As presented at Dutch PHP Conference 2015, an introduction to command buses, how to implement your own in PHP and why they're both useful but unimportant.
With more and more sites falling victim to data theft, you've probably read the list of things (not) to do to write secure code. But what else should you do to make sure your code and the rest of your web stack is secure ? In this tutorial we'll go through the basic and more advanced techniques of securing your web and database servers, securing your backend PHP code and your frontend javascript code. We'll also look at how you can build code that detects and blocks intrusion attempts and a bunch of other tips and tricks to make sure your customer data stays secure.
Go beyond the documentation and explore some of what's possible if you stretch symfony to its limits. We will look at a number of aspects of symfony 1.4 and Doctrine 1.2 and tease out some powerful functionality you may not have expected to find, but will doubtless be able to use. Topics covered will include routing, forms, the config cache and record listeners. If you're comfortable in symfony and wondering what's next, this session is for you.
What makes your code slow? How do you make it faster? And how do you prove it?
This talk will describe my adventures benchmarking and optimizing ordered hashes in Perl, culminating in the release of Hash::Ordered (http://p3rl.org/Hash::Ordered) — which outperforms all other CPAN alternatives, often by a substantial margin. We will cover:
* How to customize Benchmark.pm
* How and why to benchmark at different scales
* Why tied anything in Perl is a horrible idea
* How ordered hashes got faster from a simple algorithm change
Closing keynote, as presented at Codemotion 2014, LaraconEU 2014, Redevelop 2014, CodeConnexx 2013 and PHP North East 2014.
This presentation makes a reference to a reading list I received. For those interested, the release consists of most of the general classics, such as Gang Of Four "Design Patterns", The Pragmatic Programmer, Structure and Interpretation of Computer Programs, Domain Driven Design and a few others. The actual list remains tucked away in a box somewhere.
Polo: Desenvolvendo os problemas de inconsistência de dados em projetos Railstdc-globalcode
Sabe aquele bug que só acontece em produção? Aquela tela que renderiza um pouco diferente porque tem aqueles dados diferentes que só existem no banco de dados de prod? Ou aquele usuário maluco que causou todos aqueles corner cases porque o input dele era muito diferente? Todo mundo já passou por esses problemas! E por que essas coisas acontecem? Uma das respostas é fácil: faltaram dados. Depois de muita dor de cabeça brigando com rake db:seeds, db:migrations, muito SQL e de abrir muito rails console em produção que eu resolvi que era hora de resolver esse problema de uma maneira diferente. Foi aí que eu criei o Polo. Uma ruby gem que automatiza a criação de dumps do seu banco de dados em produção e gera amostras pra você poder importar no seu ambiente de desenvolvimento. Não perca mais tempo quebrando a cabeça com dados inconsistentes, fazendo deploys para produção só pra testar um corner case, ou abrindo console do rails em produção e brincando com a morte.
sap startup focus acelerando startups brasileiras com sap hanatdc-globalcode
A SAP lançou o SAP Startup Focus como uma iniciativa global para auxiliar Startups promissoras da área de Big Data, análise preditiva e em tempo real, a desenvolver novas aplicações em SAP HANA?, nossa revolucionária plataforma tecnológica de alta performance e banco de dados in-memory. Por meio do programa, a SAP oferece acesso irrestrito à tecnologia, além de suporte técnico na fase de desenvolvimento da solução da sua Startup e mentoria em negócios por parte de experts da indústria. Caso sua Startup passe para a fase final do programa, você terá acesso a mais de 250.000 clientes da base global da SAP para promover a sua solução e acelerar a tração de mercado. Venha conhecer o programa e fazer parte dessa rede que já conta com mais de 2000 Startups em 57 países.
A dinâmica da palestra não envolve apenas teoria, mas também codificação em um Mac com Xcode, commit o Git do Server e validação do código e testes unitários de forma automática no Xcode Server, tanto em simuladores quanto em um device conectado ao servidor. Já realizei esta palestra no TDC 2015 Floripa na trilha mobile e no Cocoa Heads de Porto Alegre, e estarei apresentando algumas novidades apresentadas no último WWDC 2015.
Dividindo para conquistar: microservicos com o jeitinho .NETtdc-globalcode
A utilização de microserviços cresceu muito em 2014. Eles ajudam a separar responsabilidades e manter o foco em grandes equipes. Nessa palestra será mostrado um exemplo prático de como utilizamos microserviços no Superplayer. Desde o projeto inicial, passando pelo seu desenvolvimento utilizando NancyFX, até a sua utilização e melhorias em produção. Quais vantagens e desvantagens na sua utilização e o futuro que vemos para este modelo.
Gerenciando recursos computacionais com Apache Mesostdc-globalcode
Sistemas com requisitos de alta escalabilidade e desempenho, demandam atenção especial no que diz respeito a Arquitetura e Operação. A sustentação de um cluster de dezenas/centenas servidores se torna inevitavelmente complexa.
Da mesma forma a Arquitetura que precisa ser projetada de forma a usar recursos do cluster de forma eficiente.
Apache Mesos atua em ambas as dimensões facilitando atividades de gerencimento e uso otimizado de recursos de cluster.
Beyond PHP - It's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
This presentation was prepared for a Webcast where John Yerhot, Engine Yard US Support Lead, and Chris Kelly, Technical Evangelist at New Relic discussed how you can scale and improve the performance of your Ruby web apps. They shared detailed guidance on issues like:
Caching strategies
Slow database queries
Background processing
Profiling Ruby applications
Picking the right Ruby web server
Sharding data
Attendees will learn how to:
Gain visibility on site performance
Improve scalability and uptime
Find and fix key bottlenecks
See the on-demand replay:
http://pages.engineyard.com/6TipsforImprovingRubyApplicationPerformance.html
Rails World 2023: Powerful Rails Features You Might Not KnowChris Oliver
I gave a talk at Rails World 2023 in Amsterdam on Powerful Rails Features You Might Not Know.
If all you've got is a hammer, everything looks like a nail. In tech, there is a constant stream of new features being added every day. Keeping up with the latest Ruby on Rails functionality can help you and your team be far more productive than you might normally be.
In this talk, we walk through a bunch of lesser known or easy to miss features in Ruby on Rails that you can use to improve your skills.
Rails is a great Ruby-based framework for producing web sites quickly and effectively. Here are a bunch of tips and best practices aimed at the Ruby newbie.
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013Joao Lucas Santana
Esta palestra apresentará as funcionalidades disponibilizadas pelo framework web Ruby on Rails desde sua primeira versão até o Rails 4. Serão apresentadas as evoluções mais significativas de cada release e as principais características do Rails 4. Ruby on Rails tem se tornado cada vez mais popular e ganhado mais adeptos. Sempre ouço comentários de desenvolvedores de outras tecnologias que desejam conhecer melhor o framework, seja para implementar projetos pessoais ou mesmo dar um novo rumo na vida profissional. Acredito que uma apresentação das evoluções implementas nesta tecnologia permitirá que muitos desenvolvedores e entusiatas obtenham um conhecimento básico, o que facilitará seus estudos posteriores permitindo que possam aprofundar mais em cada tópico coberto na palestra. A palestra não tem o objetivo de entrar em detalhes técnicos das implementações, mas sim explicar e, sempre que possível exemplificar, o que passou a ser possível de ser implementado após cada release.
ManageIQ currently runs on Ruby on Rails 3. Aaron "tenderlove" Patterson presents his effort to migrate to RoR 4, which entails some changes in the code to take advantage of the latest advances in RoR.
For more on ManageIQ, see http://manageiq.org/
fog or: How I Learned to Stop Worrying and Love the CloudWesley Beary
Learn how to easily get started on cloud computing with fog. If you can control your infrastructure choices, you’ll make better choices in development and get what you need in production. You'll get an overview of fog and concrete examples to give you a head start on your provisioning workflow.
Beyond php - it's not (just) about the codeWim Godden
Most PHP developers focus on writing code. But creating Web applications is about much more than just wrting PHP. Take a step outside the PHP cocoon and into the big PHP ecosphere to find out how small code changes can make a world of difference on servers and network. This talk is an eye-opener for developers who spend over 80% of their time coding, debugging and testing.
Many companies continue to manaully create and manage their cloud infrastructure via web consoles. Documenting these procedures is challenging, especially since the interfaces are always evolving. Reviewing the changes is also difficult, and it often involves having a coworker watching over your shoulder. Rolling back a bad change requires deleting your current work and attemtping to manually re-create the old infrastructure from memory. Scaling or deploying the infrastructure to new environments also often involves manually re-creating it.
Hashicorp's Terraform allows for the management of infrastructure as code. While a growing number of groups have started to utilize this tool, most are only just beginning to scratch the surface of its potential. Yes, Terraform can be used to create and manage resources in AWS and other cloud providers. However, thanks to an ever growing number of providers, it can manage resources in many other popular cloud services. At Yelp, we use Terraform to manage our AWS resources, DNS records in NS1, CDN configuration in Fastly and Cloudflare, and our charts and dashboards in SignalFx.
This setup provides us with the ability to maintain our infrastructure as code in a version control system that can be put through standard code review flows. If we discover an issue, we can revert to an older, working commit and restore our infrastructure to that point in time. Documentation can include code snippets that can be easily copied/pasted in an error free manner. Finally, resources managed by one Terraform provider can benefit from and utilize information from resources managed by another provider. This means that launching a new AWS EC2 instance can automatically update the necessary DNS records in NS1, and then create a dashboard filled with customized charts designed to monitor the instance.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
2. Marcelo Cajueiro
• 5 anos trabalhando com Ruby on Rails
• Engenheiro e líder no Enjoei =P
• Não toco nenhum instrumento
• Nick no chat da uol: tatuado_25_na_cam !
• http://cajueiro.me
28. gem 'octopus'
class Badge < ActiveRecord::Base
replicated_model
end
Badge.where(user_id: 1) # usa réplica
@user = User.using(:shard1).find_by_name("Joao")
PS.: use com sabedoria.
39. Uma query por usuário
User.limit(10).each do |user|
# Eu estou seguindo esse usuário?
if current_user.following.where(id: user.id).exists?
# imprime o botão "deixar de seguir"
else
# imprime o botão "seguir"
end
end
A solução mais simples geralmente não é a mais performática.
40. Salvando os ids de quem eu sigo
# E se eu estiver seguindo 90mil usuários?
following_ids = current_user.following_ids
User.limit(10).each do |user|
if following_ids.include?(user.id)
# imprime o botão "deixar de seguir"
else
# imprime o botão "seguir"
end
end
42. users = User.limit(10)
user_ids = users.map(&:id) # pluck? no :)
following_ids = current_user.
following.where(id: user_ids).pluck(:id)
users.each do |user|
if following_ids.include?(user.id)
# imprime o botão "deixar de seguir"
else
# imprime o botão "seguir"
end
end
44. Com INNER JOIN
following_ids = current_user.
following.where(id: user_ids).pluck(:id)
SELECT "users"."id"
FROM "users"
INNER JOIN "user_follows"
ON "users"."id" = "user_follows"."user_id"
WHERE "user_follows"."follower_id" = 1
45. Sem INNER JOIN
following_ids = UserFollow.
where(follower_id: current_user.id).
pluck(:user_id)
SELECT "user_follows"."user_id"
FROM "user_follows"
WHERE "user_follows"."follower_id" = 1
Nem sempre o que o Rails tem pronto é o melhor.
50. Dashboard
• data da primeira compra
• data da última compra
• número de compras
• total gasto
• categorias compradas
• marcas compradas
51. Informações triviais sozinhas
class User
def first_purchase_at
orders.minimum(:sold_at)
end
def last_purchase_at
orders.maximum(:sold_at)
end
def purchases_count
orders.count
end
end
52. Informações triviais sozinhas
class User
def purchases_total_price
orders.sum(:price)
end
def purchased_brands
purchased_products.pluck(:brand).uniq
end
def purchased_brands
purchased_products.pluck(:category).uniq
end
end
56. SQL aggregation
purchases = user.orders.select(
"max(orders.sold_at) AS last_purchased_at",
"min(orders.sold_at) AS first_purchased_at",
"sum(orders.price) AS total_price",
"count(orders.id) AS total"
).to_a.first
58. Opções
1 - todas as informacões em queries
separadas
2 - uma query com todos os dados
separados e calculando com ruby
3 - uma query com os campos
calculados e outras duas para o
restante
61. Mais um exemplo
photos.order('CASE WHEN selected = true
THEN 0
ELSE COALESCE(position, 0) + 1 END')
Ou
photos.sort_by do |photo|
if photo.selected?
0
else
photo.position.to_i + 1
end
end
64. Ordenação na query + limit
EXPLAIN SELECT * FROM messages
WHERE user_id = 1
ORDER BY id DESC LIMIT 10
Limit (cost=539.60..539.63 rows=10 width=115)
-> Sort (cost=539.60..539.94 rows=136 width=115)
Sort Key: id
-> Bitmap Heap Scan on messages
(cost=5.49..536.67 rows=136 width=115)
Recheck Cond: (user_id = 1)
-> Bitmap Index Scan on index_messages_on_user_id
(cost=0.00..5.45 rows=136 width=0)
Index Cond: (user_id = 1)
65. Usando índice com ordenação
CREATE INDEX index_messages_ordered_on_user_id
ON messages (user_id, id DESC)
Limit (cost=0.43..40.78 rows=10 width=115)
-> Index Scan using index_messages_ordered_on_user_id on messages
(cost=0.43..549.14 rows=136 width=115)
Index Cond: (user_id = 1)
66.
67. Cache
• Fragment
• Russian doll
• Rack
• HTTP
Speed Up Your Rails App by 66% - The Complete Guide to
Rails Caching 4
4
From Nate Berkopec
68. gem 'identity_cache'
class Product < ActiveRecord::Base
include IdentityCache
has_many :photos
belongs_to :category
cache_has_many :photos
cache_belongs_to :category
end
product = Product.fetch(1)
product.fetch_photos
product.fetch_category
69. class Photo < ActiveRecord::Base
include IdentityCache
cache_index :imageable_type, :imageable_id
end
class Product < ActiveRecord::Base
def cached_images
Photo.
fetch_by_imageable_type_and_imageable_id(
'Product', id
)
end
end
70. Counter cache
• Implementação do Rails
class Order < ActiveRecord::Base
belongs_to :customer, counter_cache: true
end
class Customer < ActiveRecord::Base
has_many :orders
end
@customer.orders.size
@customer.orders.count
72. Paginação
• usar o counter cache para calcular a numeração
• remover a numeração das páginas
current_user.
followers.
paginate(per_page: 10,
page: params[:page],
total_entries: current_user.followers_count)
73. Remover locks pessismistas desnecessários
Comment.lock.find(1).destroy
comment = Comment.find(1)
comment.with_lock do
comment.destroy!
end
74. Admin no servidor do usuário final
• Admin é sempre mais lento
• Tem Relatórios
• Cheio de ações demoradas
Boa solução
• Proxy reverso
75. Lazy load na interface
• Por que carregar os comentários na ação principal?
• Por que carregar os produtos relacionados na ação
principal?
• ...
76. Migration sem lock na tabela
class AddIndexToMessages < ActiveRecord::Migration
disable_ddl_transaction!
def change
add_index :messages, :user_id, algorithm: :concurrently
end
end