Your SlideShare is downloading. ×
Refactoring.the.ruby.way
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Refactoring.the.ruby.way

971
views

Published on

Published in: Technology

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
971
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Transcript

    • 1. Refactoring: The Ruby Way Shouichi KAMIYA
    • 2. Goal• Writing beautiful code in the ruby way
    • 3. Beautiful• Readable: easy to understand• Efficient: easy to write• Flexible: easy to extend
    • 4. The Ruby Way• Modular• Method chaining• English like
    • 5. class Server < ActiveRecord::Base def reload_nginx(flag = :reload) if flag == :reload ssh("user", address, "sudo /etc/init.d/nginx reload") elsif flag == :restart ssh("user", address, "sudo /etc/init.d/nginx restart") end end def reload_syslog(flag = :reload) # almost same as above endend
    • 6. Problems• Duplications• if ... else ...• The method named “reload” does “restart”
    • 7. class Server < ActiveRecord::Base def reload_nginx exec("/etc/init.d/nginx”, “restart") end def restart_nginx exec(“/etc/init.d/nginx”, “restart”) end def exec(path, arg) ssh("user", address, "sudo #{path} #{arg}") endend
    • 8. Still don’t feel right• If it is a C, it might OK but, doesn’t look very nice when it comes to ruby.
    • 9. What we wantserver = Server.find(id)server.nginx.restartserver.nginx.reload
    • 10. Modularmodule Daemons class Nginx end class Syslog endend
    • 11. How to write• User first: think of the users who use the API you designed.
    • 12. Ruby Idiomsmodule ActiveRecord class User < AR::Base class Base has_many :articles end endend
    • 13. class Base class << self def has_path(path) self.path = path end endendclass Nginx < Base has_path “/etc/init.d/nginx”endclass Syslog < Base has_path “/etc/init.d/syslog-ng”end
    • 14. class Base def exec(*args) ssh(“root”, address, “#{self.path} #{args}”) end def reload exec(:reload) end def restart exec(:restart) endend
    • 15. Finallyclass Server def nginx @nginx ||= Daemons::Nginx.new(self) endendServer.find(id).nginx.restart
    • 16. Thanks• All source codes are available at https:// gist.github.com/749800