SlideShare una empresa de Scribd logo
1 de 47
Ruby on Rails Pitfall
  Or just stupid mistakes we made

                                        Robin Lu
                                   IN-SRC Studio
                              robinlu@in-src.com
                              RubyConfChina2009
IN-SRC Studio

• http://www.in-src.com
• Team behind Caibangzi.com
• Full stack Ruby On Rails Development
• Projects from Pepboys,Vitality, Healthwise...
‘and’ or ‘&&’
What does this mean?
   result = func(arg) and render(:text => result)
‘and’ or ‘&&’
What does this mean?
   result = func(arg) and render(:text => result)

Why not this?
   result = func(arg) && render(:text => result)
‘and’ or ‘&&’
What does this mean?
   result = func(arg) and render(:text => result)

Why not this?
   result = func(arg) && render(:text => result)

Be aware of the operator precedence
strip_tags

   Display user input text without tags

What we did:
strip_tags
When
    text =
      ‘<img title=quot;http://example.com/x.js?quot; src=quot;#quot;’

the page becomes:

<p> <img title=quot;http://example.com/x.js?quot; src=quot;#quot; </p>
strip_tags

strip_tags is not safe by itself

      h strip_tags(text)
cache
class Blog1Controller < ApplicationController
   def list
     unless read_fragment(:action => 'list')
        @articles = Article.find_recent          Controller
     end
   end
end

<% cache do %>
 <ul>
 <% for article in @articles -%>
    <li><p><%= h(article.body) %></p></li>      list.html.erb
 <% end -%>
 </ul>
<% end %>
cache
Result:
     sometime got crash due to
       uninitialized @articles
cache
article list
cache
 article list

check cache
cache
 article list

check cache       list
cache
 article list

check cache       list



  render
cache
 article list            article new

check cache       list



  render
cache
 article list            article new

check cache       list   expire cache

  render
cache
 article list            article new

check cache       list   expire cache

  render
cache
 article list            article new

check cache       list   expire cache

  render

check cache
cache
    article list             article new

   check cache        list   expire cache

      render

   check cache

crashed by non-init
     @articles
cache
Solutions?

  • defensive: handle the exception
  • postpone init of @articles
  • update caches instead of expiring them
         none of them is perfect
whiny nil
whiny nil
Check nil? everywhere?
whiny nil
config.whiny_nil = true
validate_uniqueness_of
validate_uniqueness_of
We always get errors like this:

A ActiveRecord::StatementInvalid occurred in
fund#add_watch_fund:

 Mysql::Error: Duplicate entry '1234-271' for key 2:
INSERT INTO `watch_funds` (`account_id`,
`position`, `fund_id`, `created_at`) VALUES(1234, 19,
271, '2009-05-06 19:13:50')
validate_uniqueness_of
 Process A
               Process B
validate_uniqueness_of
 Process A
               Process B

  unique?
validate_uniqueness_of
 Process A
                           Process B

  unique?    select ....
validate_uniqueness_of
 Process A
                           Process B

  unique?    select ....
                            unique?
validate_uniqueness_of
 Process A
                           Process B

  unique?    select ....
                            unique?


  Insert
validate_uniqueness_of
 Process A
                           Process B

  unique?    select ....
                            unique?


  Insert
                            Insert
validate_uniqueness_of
 Process A
                           Process B

  unique?    select ....
                            unique?


  Insert
                            Insert

                           crash!
validate_uniqueness_of

  validate_uniqueness_of may not
     guarantee the uniqueness

use your own lock if the uniqueness is
           critical to you.
conditions
Background:
  • category has many subcategories
  • subcategory has many posts
  • post belongs to subcategory
we need to select all posts in a category.
conditions
What we did:
named_scope :in_category, lambda { |cat|
  conditions = [cat.subcategories.map {|subcat|
      'posts.subcategory_id = ?'
  }.join(quot; OR quot;)]
  cat.subcategories.each {|subcat|
      conditions << subcat.id }
  {:conditions => conditions}
}
conditions
Result:
  we get all posts when a category has no
               subcategories
conditions
When category has no subcategory
named_scope :in_category, lambda { |cat|
  conditions = [cat.subcategories.map {|subcat|
      'posts.subcategory_id = ?'
  }.join(quot; OR quot;)]
  cat.subcategories.each {|subcat|
      conditions << subcat.id }
  {:conditions => conditions}
}
conditions

 When you compose conditions, be
  aware that sometime nothing to
         compose means
the conditions should match nothing,
not the conditions should be empty.
before_create
   set a flag if the author of the post is an admin

What we did:
before_create
Result:

     Only post by admin can be saved
before_create


      All these callbacks are Filters
Be careful not to break the filter chain by
    what you return from the filters!
after_create
   send a mail whenever a new record is created

What we did:
after_create
Result:
  sometime the record save failed but we
         still get mail notification
after_create
   before_create              begin
                              ...
       create                 ...
                              commit
    after_create

all in one transaction   all the steps between this
                          should be transactional
after_create
What are non-transactional actions?
• send a mail
• delete a file
• expire a cache
after_create

• try not put non-transaction actions into
  transactions.
  • after_commit
  • in controller
Thanks!

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
 
Telling Stories With RSpec
Telling Stories With RSpecTelling Stories With RSpec
Telling Stories With RSpec
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
Automated Frontend Testing
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
 
Apex 5 plugins for everyone version 2018
Apex 5 plugins for everyone   version 2018Apex 5 plugins for everyone   version 2018
Apex 5 plugins for everyone version 2018
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Testing untestable code - DPC10
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10
 
Better Testing With PHP Unit
Better Testing With PHP UnitBetter Testing With PHP Unit
Better Testing With PHP Unit
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Angular Testing
Angular TestingAngular Testing
Angular Testing
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
Backday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkitBackday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkit
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Mspec talk
Mspec talkMspec talk
Mspec talk
 
Angular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of StatesAngular2 & ngrx/store: Game of States
Angular2 & ngrx/store: Game of States
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
JavaFX – 10 things I love about you
JavaFX – 10 things I love about youJavaFX – 10 things I love about you
JavaFX – 10 things I love about you
 

Destacado

Bideo-Jolasak
Bideo-JolasakBideo-Jolasak
Bideo-Jolasak
olatzucin
 
Varnish, The Good, The Awesome, and the Downright Crazy.
Varnish, The Good, The Awesome, and the Downright Crazy.Varnish, The Good, The Awesome, and the Downright Crazy.
Varnish, The Good, The Awesome, and the Downright Crazy.
Mike Willbanks
 

Destacado (20)

Social Game的技术挑战
Social Game的技术挑战Social Game的技术挑战
Social Game的技术挑战
 
Java Eye Architecture
Java Eye ArchitectureJava Eye Architecture
Java Eye Architecture
 
Why Ruby?
Why Ruby?Why Ruby?
Why Ruby?
 
Web并发模型粗浅探讨
Web并发模型粗浅探讨Web并发模型粗浅探讨
Web并发模型粗浅探讨
 
The Hybrid Tutoring Experience
The Hybrid Tutoring ExperienceThe Hybrid Tutoring Experience
The Hybrid Tutoring Experience
 
Lecture 6 Kernel Debugging + Ports Development
Lecture 6 Kernel Debugging + Ports DevelopmentLecture 6 Kernel Debugging + Ports Development
Lecture 6 Kernel Debugging + Ports Development
 
Rwservlet
RwservletRwservlet
Rwservlet
 
Lessons Learned and Best Practices for Game Development in the Cloud
Lessons Learned and Best Practices for Game Development in the CloudLessons Learned and Best Practices for Game Development in the Cloud
Lessons Learned and Best Practices for Game Development in the Cloud
 
Challenge of SHIMANE - Example of use Ruby in Japanese regional government an...
Challenge of SHIMANE - Example of use Ruby in Japanese regional government an...Challenge of SHIMANE - Example of use Ruby in Japanese regional government an...
Challenge of SHIMANE - Example of use Ruby in Japanese regional government an...
 
BizTalk Practical Course Preview
BizTalk Practical Course PreviewBizTalk Practical Course Preview
BizTalk Practical Course Preview
 
Memories of Japan
Memories of JapanMemories of Japan
Memories of Japan
 
Bideo-Jolasak
Bideo-JolasakBideo-Jolasak
Bideo-Jolasak
 
Odissea per a 4 rt de la eso
Odissea per a  4 rt de la esoOdissea per a  4 rt de la eso
Odissea per a 4 rt de la eso
 
Les 2 Informatieverzorging
Les 2 InformatieverzorgingLes 2 Informatieverzorging
Les 2 Informatieverzorging
 
christmas
christmaschristmas
christmas
 
Varnish, The Good, The Awesome, and the Downright Crazy.
Varnish, The Good, The Awesome, and the Downright Crazy.Varnish, The Good, The Awesome, and the Downright Crazy.
Varnish, The Good, The Awesome, and the Downright Crazy.
 
Temple romà
Temple romàTemple romà
Temple romà
 
Unit 2
Unit 2Unit 2
Unit 2
 
PHOTOGRAPHY
PHOTOGRAPHYPHOTOGRAPHY
PHOTOGRAPHY
 
Axiologix Company Presentation Jan 2011
Axiologix Company Presentation Jan 2011Axiologix Company Presentation Jan 2011
Axiologix Company Presentation Jan 2011
 

Similar a ruby on rails pitfalls

OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
Yi-Ting Cheng
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
Clinton Dreisbach
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
DjangoCon2008
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
DjangoCon2008
 

Similar a ruby on rails pitfalls (20)

OSDC 2009 Rails Turtorial
OSDC 2009 Rails TurtorialOSDC 2009 Rails Turtorial
OSDC 2009 Rails Turtorial
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client Development
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
Staying railsy - while scaling complexity or Ruby on Rails in Enterprise Soft...
 
Cache Money Talk: Practical Application
Cache Money Talk: Practical ApplicationCache Money Talk: Practical Application
Cache Money Talk: Practical Application
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Errors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 librariesErrors detected in the Visual C++ 2012 libraries
Errors detected in the Visual C++ 2012 libraries
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey BuzdinMarvel of Annotation Preprocessing in Java by Alexey Buzdin
Marvel of Annotation Preprocessing in Java by Alexey Buzdin
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Rails OO views
Rails OO viewsRails OO views
Rails OO views
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
High Performance Django
High Performance DjangoHigh Performance Django
High Performance Django
 
High Performance Django 1
High Performance Django 1High Performance Django 1
High Performance Django 1
 
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and PatternsRefactoring @ Mindvalley: Smells, Techniques and Patterns
Refactoring @ Mindvalley: Smells, Techniques and Patterns
 
Extracting Plugins And Gems From Rails Apps
Extracting Plugins And Gems From Rails AppsExtracting Plugins And Gems From Rails Apps
Extracting Plugins And Gems From Rails Apps
 
Rails antipattern-public
Rails antipattern-publicRails antipattern-public
Rails antipattern-public
 

Más de Robbin Fan (6)

精益创业讨论
精益创业讨论精益创业讨论
精益创业讨论
 
运营专业型社区的经验和反思
运营专业型社区的经验和反思运营专业型社区的经验和反思
运营专业型社区的经验和反思
 
缓存技术浅谈
缓存技术浅谈缓存技术浅谈
缓存技术浅谈
 
Ruby In Enterprise Development
Ruby In Enterprise DevelopmentRuby In Enterprise Development
Ruby In Enterprise Development
 
Maximes Presentation For Rubyconf China 2009
Maximes Presentation For Rubyconf China 2009Maximes Presentation For Rubyconf China 2009
Maximes Presentation For Rubyconf China 2009
 
Design Pattern From Java To Ruby
Design Pattern    From Java To RubyDesign Pattern    From Java To Ruby
Design Pattern From Java To Ruby
 

Último

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
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

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
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

ruby on rails pitfalls

Notas del editor

  1. action controller &#x76F8;&#x5173;&#x7684;&#x95EE;&#x9898; Anything you place in the flash will be exposed to the very next action and then cleared out.
  2. Anything you place in the flash will be exposed to the very next action and then cleared out.
  3. action view&#x76F8;&#x5173;
  4. &#x5728;&#x4E00;&#x4E9B;&#x6709;&#x7279;&#x6B8A;&#x5BB9;&#x9519;&#x7279;&#x6027;&#x7684;&#x6D4F;&#x89C8;&#x5668;&#x4E2D;,&#x6BD4;&#x5982;IE 6.0 &#x4E0D;&#x5B8C;&#x6574;&#x7684;tag&#x4F1A;&#x88AB;&#x62FC;&#x6210;&#x4E00;&#x4E2A;&#x5B8C;&#x6574;&#x7684;tag.
  5. not safe sanitizer:HTML::FullSanitizer safe sanitizer:HTML::WhiteListSanitizer
  6. controller + view &#x4EE3;&#x7801;&#x6765;&#x6E90;&#x4E8E;Agile Web Development With Rails
  7. active record&#x76F8;&#x5173;
  8. when there&#x2019;s no table lock
  9. when there&#x2019;s no table lock
  10. when there&#x2019;s no table lock
  11. when there&#x2019;s no table lock
  12. when there&#x2019;s no table lock
  13. when there&#x2019;s no table lock
  14. &#x5982;&#x679C;conditions&#x662F;&#x7EC4;&#x5408;&#x800C;&#x6210;&#x7684;,&#x8981;&#x6CE8;&#x610F;&#x662F;&#x5426;&#x6709;&#x7EC4;&#x5408;&#x5185;&#x5BB9;&#x4E3A;&#x7A7A;&#x7684;&#x60C5;&#x51B5;.&#x7EC4;&#x5408;&#x5185;&#x5BB9;&#x4E3A;&#x7A7A;,conditions&#x4E0D;&#x80FD;&#x4E3A;&#x7A7A;.&#x5426;&#x5219;,&#x53EF;&#x80FD;&#x5F97;&#x5230;&#x5B8C;&#x5168;&#x76F8;&#x53CD;&#x7684;&#x7ED3;&#x679C;.
  15. otherwise, something strange could happen