SlideShare a Scribd company logo
1 of 29
25 REAL LIFE TIPS IN
RUBY ON RAILS DEVELOPMENT
         Nicolas Jacobeus
            @jacobeus
THE F*CK IS THIS?


• Real   life ideas from real life apps

• Aim: elegant, secure, maintainable      apps

• Production    code

• Tips, not   rules
LET’S START

 25 24 23 22 21
 20 19 18 17 16
 15 14 13 12 11
   10 9 8 7 6
    54321
a x
nt
sy



           1. CROSS THE CHANNEL


 • Only    code in english

 • Pay    attention to the speling, but also to the meaning

 • IT    = information technology
x
               2. AVOID AWKWARD
   a
nt
sy




                     SILENCES
 • Forbid   trailing whitespaces

 • Forbid   useless empty lines

 • Forbid   space/tabs mixes

 • Why:

     • There   are people who care

     • Nobody    likes useless/noisy diff files
3. {{SOME STUPID WORD
ch
ar




               PLAY ON REST}}

 • Use   REST everywhere, by default

 • Only   difficult in some cases

     • Links   from email (always GET)

     • Interaction   without other tools (payment gateways, etc.)
ch
ar



          4. ORGANIZE YOUR APP


 • Don’t  be afraid to enhance the Rails
   directory structure

 • Tellrails about it in
   config/environment.rb
ch
ar



                   5. KICK RJS OUT


 • RJS   = Javascript written in Ruby and sent asynchronously

 • XMLHttpRequest      (XHR) is for sending data asynchronously

 • Keep   the behaviour in your behaviour (JS) files
6. CONSIDER PRESENTERS
  ch
ar




           AND CONDUCTORS
 • Presenter

   • layer   between the controller and the view

   • holds  all the presentation stuff related to your model
       (formatted currency/dates, etc.)

 • Conductor

   • layer   between the model and the controller

   • handles   multi-model forms
ls
          7. UNDERSTAND MODEL
   e
od
m




                 HOOKS

    • before_validation: forprocessing user-submitted data before
     validating it (ex.: lowercase domain name etc.)

    • before_save: for
                    saving computed stuff in the model (like
     timestamps, hashes, ...)

    • after_save: for   updating related models

    • Never   call save/update in a hook!
els
od
m



     8. ORGANIZE YOUR MODELS
    • Keep    consistent in the way you code your models

    • I’m   used to this order:

      • behavior-related stuff (usually from plugins like acts_as_...)
      • relationships (belongs_to/has_many) and named_scopes
      • validations
      • hooks
      • attributes-related stuff
      • methods grouped by aspect (authentication, messaging, ...)
els
od
m



              9. OBSERVE BY ASPECT

    • Observers    can manage multiple models

    • Make    one observer per purpose, for example

     • notification   observer

     • mail   observer

     • referral   observer
s
          10. DON’T CALL THE DB
 w
vie




             FROM YOUR VIEWS
 • MVC     : no call to the model layer from views

 • All  dynamic data should be defined in controller variables
      @users_count vs. @users.count

 • Why:

      • Separation   of concerns / loose coupling

      • Unit   testing
s
 w
vie



        11. CONSIDER HAML/SASS


 • More   concise than vanilla
      HTML/CSS

 • Prevents    you from invalid
      markup

 • HTML5-compatible
s
   er
   lp
he



                12. HELP YOUR VIEWS

  • Use     helpers for

        • repeated   chunks of view code (will DRY your views)

        • presentation
                    logic like first_tab_is_active? (will make your
         code more readable)

  • You     can also use helper_method if you need the logic in
        controllers as well
s
   er
            13. USE THE BEST
   lp
he




        LANGUAGE FOR EACH TASK


  • Generate    HTML in HTML (or Haml ;-))

  • Avoid    content_tags in helpers, rather call partials

  • Easier   for html slicers to understand
s
   er
   lp
he



                 14. HELP BY ASPECT

  • Rails   generate by default one helper per controller

  • Erase    them all and use aspect-oriented helpers

        • links_helper

        • menu_helper

        • avatar_helper
s
   er
   lp
he



    15. USE CLEVER LINK HELPERS

  • You     often have presentation logic which depends on the
        context

  • Example: a        link to a profile page in a social network

        • is   it you ? / one of your friends ? / someone else ?

        • create    link_to_user which will point to the good controller
rs
     lle
       16. MINIMIZE INTERACTIONS
  ro
nt
co




            BETWEEN C AND M

     • Only call a model once in each controller method (besides
      save/update)

     • Why:

       • Separation  of concerns (prevents inconsistency if several
         controllers deal with the same models)

       • Keep   all the logic related to the model in one place
rs
     lle
  ro
nt
co



                  17. SKINNY C, FAT M


     • Put   all business logic in your model

     • The   role of the controller layer is to

       • get   user input and send it to the model layer

       • send   the answer back to the user
rs
     lle
                18. KEEP CONSISTENT
  ro
nt
co




                    CONTROLLERS


     • Try   to keep the same order in your REST methods

     • I’mused to INCSEUD (typical workflow)
      index / new / create / show / edit / update / destroy
e
   as
                19. AVOID DATA IN
 abt
da




                    MIGRATIONS


  • There’s   a rake db:seed task for your “kickstart” data

  • For   demo/dev data, create your own rake tasks

  • Exception: refactoring-related   migrations sometimes need data
e
   as
          20. PAY ATTENTION TO
 abt
da




            RDBMS DATATYPES


  • Length    of fields

  • Varchar   vs. char vs. text

  • Integer   rather than float for currency
y
  rit
                 21. XSS-PROTECT
  cu
se




                YOUR TEXT FIELDS

  • XSS   = cross-site scripting

  • Protect   all your text fields which are manipulated by the user

  • xss_terminate   plugin

  • Don’t   protect serialized fields
y
  rit
         22. PROTECT YOUR FIELDS
  cu
se




         FROM MASS-ASSIGNMENT

  • @user.update_attributes(params[:user])   # { :admin => true }

  • Users    can forge form submission (with cURL, etc.)

  • Put    an empty attr_accessible clause in each model upon
       creation, and add “safe” fields one by one
y
  rit
  cu
se



             23. SCOPE BY DEFAULT

  • In   your controllers, scope every request to the current user

       • current_user.messages.find(params[:id])

       • current_user.messages.build(params[:message])

  • Even    in methods where it’s not necessary (like new), for
       consistency
y
   plo

          24. DEPLOY WITH GREAT
de




                  TOOLS


  • What   works well for us (for the moment!):

     • Ruby   Enterprise Edition + nginx + Capistrano + GitHub

     • Heroku
isc
m



                        25. USE RUBY

• In   case you didn’t know, Rails is based on it.

• Embrace      functional programming
    thing.select {|t| t.valid?}.map {|t| t.stuff}.flatten.uniq

• Don’t    be afraid of meta-programming, it can help you!

    • Create   domain-specific languages for your app

    • Generate    groups of similar methods at once
THANKS


This is the last slide, ‘cause my talk is over.

More Related Content

What's hot

Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web ApplicationYakov Fain
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSShekhar Gulati
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
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 AppsMike Subelsky
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
devise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwandevise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwanTse-Ching Ho
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationSociable
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsStacy London
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Antonio Peric-Mazar
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
 

What's hot (20)

Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
MVS: An angular MVC
MVS: An angular MVCMVS: An angular MVC
MVS: An angular MVC
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Rails3 changesets
Rails3 changesetsRails3 changesets
Rails3 changesets
 
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
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
devise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwandevise tutorial - 2011 rubyconf taiwan
devise tutorial - 2011 rubyconf taiwan
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
Vuejs testing
Vuejs testingVuejs testing
Vuejs testing
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Refactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.jsRefactoring Large Web Applications with Backbone.js
Refactoring Large Web Applications with Backbone.js
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Workshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte III
 

Viewers also liked

Real Time with Rails 5
Real Time with Rails 5Real Time with Rails 5
Real Time with Rails 5Lucas Renan
 
Presentación 757 niversario puebla de cangas
Presentación 757 niversario puebla de cangasPresentación 757 niversario puebla de cangas
Presentación 757 niversario puebla de cangasobanca
 
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...FESD GKr
 
Pozyskiwanie inwestora na przykładzie ServeCloud.pl
Pozyskiwanie inwestora na przykładzie ServeCloud.plPozyskiwanie inwestora na przykładzie ServeCloud.pl
Pozyskiwanie inwestora na przykładzie ServeCloud.plSpodek 2.0
 
Embajadas y consulados de mexico en el mundo
Embajadas y consulados de mexico en el mundoEmbajadas y consulados de mexico en el mundo
Embajadas y consulados de mexico en el mundoRafael Franyutti
 
Medicare Step By Step
Medicare  Step By StepMedicare  Step By Step
Medicare Step By Stepdparalegal
 
2 steroid metabolism
2   steroid metabolism2   steroid metabolism
2 steroid metabolismMUBOSScz
 
MARKETING Y SENTIDO COMUN
MARKETING Y SENTIDO COMUNMARKETING Y SENTIDO COMUN
MARKETING Y SENTIDO COMUNF BENAVIDEZ
 
Integrasjoner esa og ephorte
Integrasjoner esa og ephorteIntegrasjoner esa og ephorte
Integrasjoner esa og ephorteRagnar Sturtzel
 
Module 2 Guidelines In Giving Emergency Care
Module 2   Guidelines In Giving Emergency CareModule 2   Guidelines In Giving Emergency Care
Module 2 Guidelines In Giving Emergency CareJack Frost
 
Rsc Gamesa alberto gallego
Rsc Gamesa alberto gallegoRsc Gamesa alberto gallego
Rsc Gamesa alberto gallegoAlberto Gallego
 

Viewers also liked (20)

Real Time with Rails 5
Real Time with Rails 5Real Time with Rails 5
Real Time with Rails 5
 
Git Tutorial
Git TutorialGit Tutorial
Git Tutorial
 
Action cable
Action cableAction cable
Action cable
 
Presentación 757 niversario puebla de cangas
Presentación 757 niversario puebla de cangasPresentación 757 niversario puebla de cangas
Presentación 757 niversario puebla de cangas
 
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...
Die Beschäftigungseffekte der experi-mentellen Arbeitsmarktpolitik der 1980er...
 
Cyprus Shipping Law
Cyprus Shipping LawCyprus Shipping Law
Cyprus Shipping Law
 
COMPANY PROFILE 3
COMPANY PROFILE 3COMPANY PROFILE 3
COMPANY PROFILE 3
 
Pozyskiwanie inwestora na przykładzie ServeCloud.pl
Pozyskiwanie inwestora na przykładzie ServeCloud.plPozyskiwanie inwestora na przykładzie ServeCloud.pl
Pozyskiwanie inwestora na przykładzie ServeCloud.pl
 
My lssu guide
My lssu guideMy lssu guide
My lssu guide
 
Demanda actual y futuro del turismo sostenible
Demanda actual y futuro del turismo sostenibleDemanda actual y futuro del turismo sostenible
Demanda actual y futuro del turismo sostenible
 
Embajadas y consulados de mexico en el mundo
Embajadas y consulados de mexico en el mundoEmbajadas y consulados de mexico en el mundo
Embajadas y consulados de mexico en el mundo
 
Wm pricelist
Wm pricelistWm pricelist
Wm pricelist
 
Medicare Step By Step
Medicare  Step By StepMedicare  Step By Step
Medicare Step By Step
 
2 steroid metabolism
2   steroid metabolism2   steroid metabolism
2 steroid metabolism
 
Buscadores de internet
Buscadores de internetBuscadores de internet
Buscadores de internet
 
Slideshard
SlideshardSlideshard
Slideshard
 
MARKETING Y SENTIDO COMUN
MARKETING Y SENTIDO COMUNMARKETING Y SENTIDO COMUN
MARKETING Y SENTIDO COMUN
 
Integrasjoner esa og ephorte
Integrasjoner esa og ephorteIntegrasjoner esa og ephorte
Integrasjoner esa og ephorte
 
Module 2 Guidelines In Giving Emergency Care
Module 2   Guidelines In Giving Emergency CareModule 2   Guidelines In Giving Emergency Care
Module 2 Guidelines In Giving Emergency Care
 
Rsc Gamesa alberto gallego
Rsc Gamesa alberto gallegoRsc Gamesa alberto gallego
Rsc Gamesa alberto gallego
 

Similar to 25 Real Life Tips In Ruby on Rails Development

MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCUlrich Krause
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesUlrich Krause
 
Meetup. Technologies Intro for Non-Tech People
Meetup. Technologies Intro for Non-Tech PeopleMeetup. Technologies Intro for Non-Tech People
Meetup. Technologies Intro for Non-Tech PeopleIT Arena
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
Ruby on Rails & Version Control
Ruby on Rails & Version ControlRuby on Rails & Version Control
Ruby on Rails & Version ControlYash Mittal
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & ArchitectureMassimo Oliviero
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsTaylor Lovett
 
Frameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic ReviewFrameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic Reviewnetc2012
 
Engage 2020 - Best Practices for analyzing Domino Applications
Engage 2020 - Best Practices for analyzing Domino ApplicationsEngage 2020 - Best Practices for analyzing Domino Applications
Engage 2020 - Best Practices for analyzing Domino Applicationspanagenda
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails newPaul Oguda
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development SecuritySam Bowne
 
Hpc lunch and learn
Hpc lunch and learnHpc lunch and learn
Hpc lunch and learnJohn D Almon
 
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...Serdar Basegmez
 
Microservices: Yes or not?
Microservices: Yes or not?Microservices: Yes or not?
Microservices: Yes or not?Eduard Tomàs
 

Similar to 25 Real Life Tips In Ruby on Rails Development (20)

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVC
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPages
 
Meetup. Technologies Intro for Non-Tech People
Meetup. Technologies Intro for Non-Tech PeopleMeetup. Technologies Intro for Non-Tech People
Meetup. Technologies Intro for Non-Tech People
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Ruby on Rails & Version Control
Ruby on Rails & Version ControlRuby on Rails & Version Control
Ruby on Rails & Version Control
 
Building iOS App Project & Architecture
Building iOS App Project & ArchitectureBuilding iOS App Project & Architecture
Building iOS App Project & Architecture
 
Where to save my data, for devs!
Where to save my data, for devs!Where to save my data, for devs!
Where to save my data, for devs!
 
Best Practices for Building WordPress Applications
Best Practices for Building WordPress ApplicationsBest Practices for Building WordPress Applications
Best Practices for Building WordPress Applications
 
Apache Drill (ver. 0.2)
Apache Drill (ver. 0.2)Apache Drill (ver. 0.2)
Apache Drill (ver. 0.2)
 
Frameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic ReviewFrameworks Galore: A Pragmatic Review
Frameworks Galore: A Pragmatic Review
 
Engage 2020 - Best Practices for analyzing Domino Applications
Engage 2020 - Best Practices for analyzing Domino ApplicationsEngage 2020 - Best Practices for analyzing Domino Applications
Engage 2020 - Best Practices for analyzing Domino Applications
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails new
 
8. Software Development Security
8. Software Development Security8. Software Development Security
8. Software Development Security
 
Hpc lunch and learn
Hpc lunch and learnHpc lunch and learn
Hpc lunch and learn
 
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...
IBM Connect 2017: Your Data In the Major Leagues: A Practical Guide to REST S...
 
Show Some Spine!
Show Some Spine!Show Some Spine!
Show Some Spine!
 
Microservices: Yes or not?
Microservices: Yes or not?Microservices: Yes or not?
Microservices: Yes or not?
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

25 Real Life Tips In Ruby on Rails Development

  • 1. 25 REAL LIFE TIPS IN RUBY ON RAILS DEVELOPMENT Nicolas Jacobeus @jacobeus
  • 2. THE F*CK IS THIS? • Real life ideas from real life apps • Aim: elegant, secure, maintainable apps • Production code • Tips, not rules
  • 3. LET’S START 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 54321
  • 4. a x nt sy 1. CROSS THE CHANNEL • Only code in english • Pay attention to the speling, but also to the meaning • IT = information technology
  • 5. x 2. AVOID AWKWARD a nt sy SILENCES • Forbid trailing whitespaces • Forbid useless empty lines • Forbid space/tabs mixes • Why: • There are people who care • Nobody likes useless/noisy diff files
  • 6. 3. {{SOME STUPID WORD ch ar PLAY ON REST}} • Use REST everywhere, by default • Only difficult in some cases • Links from email (always GET) • Interaction without other tools (payment gateways, etc.)
  • 7. ch ar 4. ORGANIZE YOUR APP • Don’t be afraid to enhance the Rails directory structure • Tellrails about it in config/environment.rb
  • 8. ch ar 5. KICK RJS OUT • RJS = Javascript written in Ruby and sent asynchronously • XMLHttpRequest (XHR) is for sending data asynchronously • Keep the behaviour in your behaviour (JS) files
  • 9. 6. CONSIDER PRESENTERS ch ar AND CONDUCTORS • Presenter • layer between the controller and the view • holds all the presentation stuff related to your model (formatted currency/dates, etc.) • Conductor • layer between the model and the controller • handles multi-model forms
  • 10. ls 7. UNDERSTAND MODEL e od m HOOKS • before_validation: forprocessing user-submitted data before validating it (ex.: lowercase domain name etc.) • before_save: for saving computed stuff in the model (like timestamps, hashes, ...) • after_save: for updating related models • Never call save/update in a hook!
  • 11. els od m 8. ORGANIZE YOUR MODELS • Keep consistent in the way you code your models • I’m used to this order: • behavior-related stuff (usually from plugins like acts_as_...) • relationships (belongs_to/has_many) and named_scopes • validations • hooks • attributes-related stuff • methods grouped by aspect (authentication, messaging, ...)
  • 12. els od m 9. OBSERVE BY ASPECT • Observers can manage multiple models • Make one observer per purpose, for example • notification observer • mail observer • referral observer
  • 13. s 10. DON’T CALL THE DB w vie FROM YOUR VIEWS • MVC : no call to the model layer from views • All dynamic data should be defined in controller variables @users_count vs. @users.count • Why: • Separation of concerns / loose coupling • Unit testing
  • 14. s w vie 11. CONSIDER HAML/SASS • More concise than vanilla HTML/CSS • Prevents you from invalid markup • HTML5-compatible
  • 15. s er lp he 12. HELP YOUR VIEWS • Use helpers for • repeated chunks of view code (will DRY your views) • presentation logic like first_tab_is_active? (will make your code more readable) • You can also use helper_method if you need the logic in controllers as well
  • 16. s er 13. USE THE BEST lp he LANGUAGE FOR EACH TASK • Generate HTML in HTML (or Haml ;-)) • Avoid content_tags in helpers, rather call partials • Easier for html slicers to understand
  • 17. s er lp he 14. HELP BY ASPECT • Rails generate by default one helper per controller • Erase them all and use aspect-oriented helpers • links_helper • menu_helper • avatar_helper
  • 18. s er lp he 15. USE CLEVER LINK HELPERS • You often have presentation logic which depends on the context • Example: a link to a profile page in a social network • is it you ? / one of your friends ? / someone else ? • create link_to_user which will point to the good controller
  • 19. rs lle 16. MINIMIZE INTERACTIONS ro nt co BETWEEN C AND M • Only call a model once in each controller method (besides save/update) • Why: • Separation of concerns (prevents inconsistency if several controllers deal with the same models) • Keep all the logic related to the model in one place
  • 20. rs lle ro nt co 17. SKINNY C, FAT M • Put all business logic in your model • The role of the controller layer is to • get user input and send it to the model layer • send the answer back to the user
  • 21. rs lle 18. KEEP CONSISTENT ro nt co CONTROLLERS • Try to keep the same order in your REST methods • I’mused to INCSEUD (typical workflow) index / new / create / show / edit / update / destroy
  • 22. e as 19. AVOID DATA IN abt da MIGRATIONS • There’s a rake db:seed task for your “kickstart” data • For demo/dev data, create your own rake tasks • Exception: refactoring-related migrations sometimes need data
  • 23. e as 20. PAY ATTENTION TO abt da RDBMS DATATYPES • Length of fields • Varchar vs. char vs. text • Integer rather than float for currency
  • 24. y rit 21. XSS-PROTECT cu se YOUR TEXT FIELDS • XSS = cross-site scripting • Protect all your text fields which are manipulated by the user • xss_terminate plugin • Don’t protect serialized fields
  • 25. y rit 22. PROTECT YOUR FIELDS cu se FROM MASS-ASSIGNMENT • @user.update_attributes(params[:user]) # { :admin => true } • Users can forge form submission (with cURL, etc.) • Put an empty attr_accessible clause in each model upon creation, and add “safe” fields one by one
  • 26. y rit cu se 23. SCOPE BY DEFAULT • In your controllers, scope every request to the current user • current_user.messages.find(params[:id]) • current_user.messages.build(params[:message]) • Even in methods where it’s not necessary (like new), for consistency
  • 27. y plo 24. DEPLOY WITH GREAT de TOOLS • What works well for us (for the moment!): • Ruby Enterprise Edition + nginx + Capistrano + GitHub • Heroku
  • 28. isc m 25. USE RUBY • In case you didn’t know, Rails is based on it. • Embrace functional programming thing.select {|t| t.valid?}.map {|t| t.stuff}.flatten.uniq • Don’t be afraid of meta-programming, it can help you! • Create domain-specific languages for your app • Generate groups of similar methods at once
  • 29. THANKS This is the last slide, ‘cause my talk is over.