Our Presentation Will Begin ShortlyRails AntiPatternsWorkshopMay 12, 2011          Matt Reider, Director of Training      ...
Rake Tasks
Are you testing them?
What makes them hard to test?   • Scripts that live outside app   • Often have network and file access   • Often have output
Example Tasknamespace :twitter do  task :search => :environment do    puts "Searching twitter."    Twitter.search("@cpytel...
One possible way to test
context "rake twitter:search" do  setup do    # How slow is this going to be? Very.    @out = `cd #{Rails.root} &&        ...
should "print a message at the beginning" do  assert_match /Searching/i, @outend
should "find all tweets containing @cpytel" do  # this one would be based entirely on luck.end
This Has Problems• Slow• No mocking or stubbing available• Task isn’t in a transaction
Basically, no sandboxing
How do we fix this?
Rake tasks are just Ruby
Move it all into the Model
class Alert < ActiveRecord::Base  def self.create_all_from_twitter_search(output = $stdout)    output.puts "Searching twit...
The Task is Nice and Skinnynamespace :twitter do  task :search => :environment do    Alert.create_all_from_twitter_search ...
Testing is Pretty Normal# test/unit/alert_test.rbclass AlertTest < ActiveSupport::TestCase  context "create_all_from_twitt...
should "print a message at the beginning" do  Alert.create_all_from_twitter_search(@output)  assert_match /Searching/i, @o...
should "save some cache files" do  Twitter.stubs(:search).returns(["one"])  alert = mock("alert")  alert.expects(:save_cac...
should "find all tweets containing @cpytel" do  Twitter.expects(:search).          with("@cpytel").          returns(["bod...
We can mock and stub!
We can use normal tools!• FakeWeb/WebMock• FileUtils::NoWrite
In Summary• You can test drive development of  your rake tasks• Rake tasks should live inside a  model (or class)
Views
Know Your Helpers
Know How They Change
# Edit form<%= form_for :user,             :url => user_path(@user),             :html => {:method => :put} do |form| %>
<%= form_for @user do |form| %>
<!-- posts/index.html.erb --><% @posts.each do |post| -%>  <h2><%= post.title %></h2>  <%= format_content post.body %>  <p...
Move the post content    into a partial
<!-- posts/index.html.erb --><% @posts.each do |post| -%>  <%= render :partial => post, :object => :post %><% end -%><!-- ...
Looping was built  into render
<!-- posts/index.html.erb --><%= render :partial => post, :collection => @posts %><!-- posts/_post.erb --><h2><%= post.tit...
<!-- posts/index.html.erb --><%= render :partial => post, :collection => @posts %><!-- posts/_post.erb --><h2><%= post.tit...
<%= render :partial => @posts %>
<%= render @posts %>
Dynamic Page Titles
<!-- layouts/application.html.erb --><head>  <title>    Acme Widgets : TX-300 Utility Widget  </title></head>
class PagesController < ApplicationController  def show    @widget = Widgets.find(params[:id])    @title = @widget.name  e...
This is all View
There is a Helper
<!-- layouts/application.html.erb --><head>  <title>    Acme Widgets : <%= yield(:title) %>  </title></head><!-- widgets/s...
Default Title
<!-- layouts/application.html.erb --><head>  <title>    Acme Widgets : <%= yield(:title) || "Home" %>  </title></head>
What else can we use      this for?
<!-- layouts/application.html.erb --><div class="sidebar">  This is content for the sidebar.  <%= link_to "Your Account", ...
<!-- layouts/application.html.erb --><%= yield(:sidebar) %><div class="main">  The main content of the page</div><!-- layo...
Avoid Duplication
<!-- layouts/application.html.erb --><div class="sidebar">  <%= yield(:sidebar) %></div><div class="main">  The main conte...
Conditional Sidebar<!-- layouts/application.html.erb --><% if content_for?(:sidebar) -%>  <div class="sidebar">    <%= yie...
Upcoming ClassesZero to Rails 3 in four days•May 23-26•VirtualRails AntiPatterns•Best Practices•Boston – June 6 & 7•San Fr...
Upcoming SlideShare
Loading in …5
×

Rails Antipatterns | Open Session with Chad Pytel

4,006 views

Published on

As developers worldwide have adopted the Ruby on Rails web framework, many have fallen victim to common mistakes that reduce code quality, performance, reliability, stability, scalability, and maintainability. Even experienced developers will find that they can reevaluate the work they've done and make it better.
In this session, Chad Pytel will provide an overview of some of these common mistakes as well as take questions from the audience and provide real-world advice. Bring your issues and get expert advice on how to bring your code in line with today's best practices.

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
4,006
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
57
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Rails Antipatterns | Open Session with Chad Pytel

    1. 1. Our Presentation Will Begin ShortlyRails AntiPatternsWorkshopMay 12, 2011 Matt Reider, Director of Training Engine Yard Chad Pytel, Founder & CEO thoughtbot Inc.
    2. 2. Rake Tasks
    3. 3. Are you testing them?
    4. 4. What makes them hard to test? • Scripts that live outside app • Often have network and file access • Often have output
    5. 5. Example Tasknamespace :twitter do task :search => :environment do puts "Searching twitter." Twitter.search("@cpytel").each do |result| puts "Processing #{result.inspect}." alert = Alert.create(:body => result) alert.save_cache_file! end end puts "All done!"end
    6. 6. One possible way to test
    7. 7. context "rake twitter:search" do setup do # How slow is this going to be? Very. @out = `cd #{Rails.root} && rake twitter:search 2>&1` end
    8. 8. should "print a message at the beginning" do assert_match /Searching/i, @outend
    9. 9. should "find all tweets containing @cpytel" do # this one would be based entirely on luck.end
    10. 10. This Has Problems• Slow• No mocking or stubbing available• Task isn’t in a transaction
    11. 11. Basically, no sandboxing
    12. 12. How do we fix this?
    13. 13. Rake tasks are just Ruby
    14. 14. Move it all into the Model
    15. 15. class Alert < ActiveRecord::Base def self.create_all_from_twitter_search(output = $stdout) output.puts "Searching twitter." Twitter.search("@cpytel").each do |result| output.puts "Processing #{result.inspect}." alert = create(:body => result) alert.save_cache_file! end output.puts "All done!" end def save_cache_file! # Removes a file from the filesystem. endend
    16. 16. The Task is Nice and Skinnynamespace :twitter do task :search => :environment do Alert.create_all_from_twitter_search endend
    17. 17. Testing is Pretty Normal# test/unit/alert_test.rbclass AlertTest < ActiveSupport::TestCase context "create_all_from_twitter_search" do setup do # Make sure none of the tests below hit the # network or touch the filesystem. Alert.any_instance.stubs(:save_cache_file!) Twitter.stubs(:search).returns([]) @output = StringIO.new end
    18. 18. should "print a message at the beginning" do Alert.create_all_from_twitter_search(@output) assert_match /Searching/i, @output.stringend
    19. 19. should "save some cache files" do Twitter.stubs(:search).returns(["one"]) alert = mock("alert") alert.expects(:save_cache_file!) Alert.stubs(:create).returns(alert) Alert.create_all_from_twitter_search(@output)end
    20. 20. should "find all tweets containing @cpytel" do Twitter.expects(:search). with("@cpytel"). returns(["body"]) Alert.create_all_from_twitter_search(@output)end
    21. 21. We can mock and stub!
    22. 22. We can use normal tools!• FakeWeb/WebMock• FileUtils::NoWrite
    23. 23. In Summary• You can test drive development of your rake tasks• Rake tasks should live inside a model (or class)
    24. 24. Views
    25. 25. Know Your Helpers
    26. 26. Know How They Change
    27. 27. # Edit form<%= form_for :user, :url => user_path(@user), :html => {:method => :put} do |form| %>
    28. 28. <%= form_for @user do |form| %>
    29. 29. <!-- posts/index.html.erb --><% @posts.each do |post| -%> <h2><%= post.title %></h2> <%= format_content post.body %> <p> <%= link_to Email author, mail_to(post.user.email) %> </p><% end -%>
    30. 30. Move the post content into a partial
    31. 31. <!-- posts/index.html.erb --><% @posts.each do |post| -%> <%= render :partial => post, :object => :post %><% end -%><!-- posts/_post.erb --><h2><%= post.title %></h2><%= format_content post.body %><p><%= link_to Email author,mail_to(post.user.email) %></p>
    32. 32. Looping was built into render
    33. 33. <!-- posts/index.html.erb --><%= render :partial => post, :collection => @posts %><!-- posts/_post.erb --><h2><%= post.title %></h2><%= format_content post.body %><p> <%= link_to Email author, mail_to(post.user.email) %></p>
    34. 34. <!-- posts/index.html.erb --><%= render :partial => post, :collection => @posts %><!-- posts/_post.erb --><h2><%= post.title %></h2><%= format_content post.body %><p> <%= link_to Email author, mail_to(post.user.email) %></p>
    35. 35. <%= render :partial => @posts %>
    36. 36. <%= render @posts %>
    37. 37. Dynamic Page Titles
    38. 38. <!-- layouts/application.html.erb --><head> <title> Acme Widgets : TX-300 Utility Widget </title></head>
    39. 39. class PagesController < ApplicationController def show @widget = Widgets.find(params[:id]) @title = @widget.name endend<!-- layouts/application.html.erb --><head> <title>Acme Widgets : <%= @title %></title></head>
    40. 40. This is all View
    41. 41. There is a Helper
    42. 42. <!-- layouts/application.html.erb --><head> <title> Acme Widgets : <%= yield(:title) %> </title></head><!-- widgets/show.html.erb --><% content_for :title, @widget.title %>
    43. 43. Default Title
    44. 44. <!-- layouts/application.html.erb --><head> <title> Acme Widgets : <%= yield(:title) || "Home" %> </title></head>
    45. 45. What else can we use this for?
    46. 46. <!-- layouts/application.html.erb --><div class="sidebar"> This is content for the sidebar. <%= link_to "Your Account", account_url %></div><div class="main"> The main content of the page</div>
    47. 47. <!-- layouts/application.html.erb --><%= yield(:sidebar) %><div class="main"> The main content of the page</div><!-- layouts/application.html.erb --><% content_for :sidebar do %> <div class="sidebar"> This is content for the sidebar. <%= link_to "Your Account", account_url %> </div><% end %>
    48. 48. Avoid Duplication
    49. 49. <!-- layouts/application.html.erb --><div class="sidebar"> <%= yield(:sidebar) %></div><div class="main"> The main content of the page</div><!-- layouts/application.html.erb --><% content_for :sidebar do %> This is content for the sidebar. <%= link_to "Your Account", account_url %><% end %>
    50. 50. Conditional Sidebar<!-- layouts/application.html.erb --><% if content_for?(:sidebar) -%> <div class="sidebar"> <%= yield(:sidebar) %> </div><% end -%><div class="main"> The main content of the page</div><!-- app/views/products/show.html.erb --><% content_for :sidebar do %> This is content for the sidebar. <%= link_to "Your Account", account_url %><% end %>
    51. 51. Upcoming ClassesZero to Rails 3 in four days•May 23-26•VirtualRails AntiPatterns•Best Practices•Boston – June 6 & 7•San Francisco – June 13 & 14 Learn more at: Engineyard.com/university

    ×