SlideShare a Scribd company logo
1 of 16
Refactoring: The Ruby
        Way
      Shouichi KAMIYA
Goal


•   Writing beautiful code in the ruby way
Beautiful


• Readable: easy to understand
• Efficient: easy to write
• Flexible: easy to extend
The Ruby Way


• Modular
• Method chaining
• English like
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
 end
end
Problems


• Duplications
• if ... else ...
• The method named “reload” does “restart”
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}")
 end
end
Still don’t feel right


• If it is a C, it might OK but, doesn’t look
  very nice when it comes to ruby.
What we want

server = Server.find(id)
server.nginx.restart
server.nginx.reload
Modular
module Daemons
 class Nginx
 end
 class Syslog
 end
end
How to write


• User first: think of the users who use the
  API you designed.
Ruby Idioms

module ActiveRecord
                      class User < AR::Base
 class Base
                       has_many :articles
 end
                      end
end
class Base
  class << self
    def has_path(path)
     self.path = path
    end
  end
end

class Nginx < Base
  has_path “/etc/init.d/nginx”
end

class Syslog < Base
  has_path “/etc/init.d/syslog-ng”
end
class Base
  def exec(*args)
   ssh(“root”, address, “#{self.path} #{args}”)
  end

 def reload
  exec(:reload)
 end

 def restart
  exec(:restart)
 end
end
Finally
class Server
 def nginx
  @nginx ||= Daemons::Nginx.new(self)
 end
end
Server.find(id).nginx.restart
Thanks


• All source codes are available at https://
  gist.github.com/749800

More Related Content

What's hot

Internals - Exploring the webOS Browser and JavaScript
Internals - Exploring the webOS Browser and JavaScriptInternals - Exploring the webOS Browser and JavaScript
Internals - Exploring the webOS Browser and JavaScriptfpatton
 
Compass VS Less
Compass VS LessCompass VS Less
Compass VS LessSarah Hick
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS IntroNgoc Dao
 
Virtual Infrastructure
Virtual InfrastructureVirtual Infrastructure
Virtual InfrastructureBryan McLellan
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs Irfan Maulana
 
Debugging webOS applications
Debugging webOS applicationsDebugging webOS applications
Debugging webOS applicationsfpatton
 
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen Anh
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen AnhOGDC Datastorage Solution_Mr.Dung, Dinh Nguyen Anh
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen AnhBuff Nguyen
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)xSawyer
 
HTTP cache: keeping it fresh
HTTP cache: keeping it freshHTTP cache: keeping it fresh
HTTP cache: keeping it freshDavid de Boer
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with PuppetKris Buytaert
 
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...LumoSpark
 
Server side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPServer side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPMarc Gear
 
Ruby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxRuby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxMathieu Elie
 

What's hot (20)

Internals - Exploring the webOS Browser and JavaScript
Internals - Exploring the webOS Browser and JavaScriptInternals - Exploring the webOS Browser and JavaScript
Internals - Exploring the webOS Browser and JavaScript
 
Compass VS Less
Compass VS LessCompass VS Less
Compass VS Less
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
Virtual Infrastructure
Virtual InfrastructureVirtual Infrastructure
Virtual Infrastructure
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
Ruby e xmpp
Ruby e xmppRuby e xmpp
Ruby e xmpp
 
Debugging webOS applications
Debugging webOS applicationsDebugging webOS applications
Debugging webOS applications
 
Start using vagrant now!
Start using vagrant now!Start using vagrant now!
Start using vagrant now!
 
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen Anh
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen AnhOGDC Datastorage Solution_Mr.Dung, Dinh Nguyen Anh
OGDC Datastorage Solution_Mr.Dung, Dinh Nguyen Anh
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)
 
HTTP cache: keeping it fresh
HTTP cache: keeping it freshHTTP cache: keeping it fresh
HTTP cache: keeping it fresh
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
How to turn any dynamic website into a static site | 24.01.2018 | Artem Danil...
 
Apache
ApacheApache
Apache
 
Nodejs web,db,hosting
Nodejs web,db,hostingNodejs web,db,hosting
Nodejs web,db,hosting
 
Server side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHPServer side scripting smack down - Node.js vs PHP
Server side scripting smack down - Node.js vs PHP
 
Conair
ConairConair
Conair
 
Ruby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdxRuby eventmachine pres at rubybdx
Ruby eventmachine pres at rubybdx
 
WebSocket
WebSocketWebSocket
WebSocket
 

Similar to Refactoring.the.ruby.way

PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)xSawyer
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby TeamArto Artnik
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015Alex S
 
Automating complex infrastructures with Puppet
Automating complex infrastructures with PuppetAutomating complex infrastructures with Puppet
Automating complex infrastructures with PuppetKris Buytaert
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of AnsibleDevOps Ltd.
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009Jason Davies
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With YouDalibor Gogic
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmersxSawyer
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) RoundupWayne Carter
 

Similar to Refactoring.the.ruby.way (20)

PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015
 
Get your teeth into Plack
Get your teeth into PlackGet your teeth into Plack
Get your teeth into Plack
 
Automating complex infrastructures with Puppet
Automating complex infrastructures with PuppetAutomating complex infrastructures with Puppet
Automating complex infrastructures with Puppet
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of Ansible
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
Rack
RackRack
Rack
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
Logstash
LogstashLogstash
Logstash
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmers
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 

Recently uploaded

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Refactoring.the.ruby.way

  • 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 end end
  • 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}") end end
  • 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 want server = Server.find(id) server.nginx.restart server.nginx.reload
  • 10. Modular module Daemons class Nginx end class Syslog end end
  • 11. How to write • User first: think of the users who use the API you designed.
  • 12. Ruby Idioms module ActiveRecord class User < AR::Base class Base has_many :articles end end end
  • 13. class Base class << self def has_path(path) self.path = path end end end class Nginx < Base has_path “/etc/init.d/nginx” end class 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) end end
  • 15. Finally class Server def nginx @nginx ||= Daemons::Nginx.new(self) end end Server.find(id).nginx.restart
  • 16. Thanks • All source codes are available at https:// gist.github.com/749800

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n