SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
Rails Tips and Best Practices
   By David Keener

            http://www.keenertech.com

                                        Version 1.1 - April 28, 2012
Introduction

Ruby on Rails is an exciting technology…a well-
crafted framework with innovative philosophies
baked in to facilitate Agile Web Development

            • But even so, there are pitfalls…

            •     A few simple tips can help you avoid
            •     the most common pitfalls
The Log File is Your Friend

You can’t optimize if you don’t know what your
code is doing -- leverage the log file….

                   • Beginning Rails developers write
                     inefficient code
                     - Log File: /log/development.log
                   • Shows all web page parameters
                     - Posted Fields
                     - URL Parameters
                   • Shows all executed SQL
A Sample Log File
Processing LoginController#index (for 127.0.0.1 at 2009-08-27 03:33:44) [POST]
Parameters: {"x"=>"25", "y"=>"10”, "authenticity_token"=>"bVOEM1qk1F4AH0=",
    "login_name"=>"dkeener@keenertech.com", "password"=>”sample"}
[4;36;1mUser Columns (2.5ms)[0m [0;1mSHOW FIELDS FROM `users`[0m
 [4;35;1mUser Load (40.8ms)[0m [0mSELECT * FROM `users` WHERE
    (`users`.`password` = ’gHyfrds76jD' AND `users`.`email` =
    'dkeener@keenertech.com') LIMIT 1[0m
[4;36;1mProfile Columns (2.1ms)[0m [0;1mSHOW FIELDS FROM `profiles`[0m
[4;35;1mProfile Load (1.2ms)[0m [0mSELECT * FROM `profiles` WHERE
    (`profiles`.`user_id` = 3) LIMIT 1[0m
[4;36;1mUser Update (0.3ms)[0m [0;1mUPDATE `users` SET `login_count` = 4,
    `updated_at` = '2009-08-27 07:33:45' WHERE `id` = 3[0m
Redirected to http://127.0.0.1:3000/
Completed in 624ms (DB: 48) | 302 Found [http://127.0.0.1/login]
My Program Blew Up on a Query
“I was doing a find(45) and my code blew up!”

      • find(#) raises a RecordNotFound exception if
        it doesn’t find a matching row

      • But find_by_id(#) returns nil if not found

      • And the first, all and last methods return
        nil if they fail

      It’s easy to forget about this…
Column Definitions
Rails makes building your database easy…
rails generate model User first_name:string
   last_name:string login_name:string
   password:string

      • Defaults to NULL-able columns
        - If it’s required, it should be NOT NULL
      • Strings => varchar(255)
        - Why worry about storage? Just use the default size
        - Let model validations handle size constraints (if any)
A Typical Migration (Excerpt)
def self.up
 create_table :users do |t|
    t.string :first_name, :null => false
    t.string :last_name, :null => false
    t.string :login_name, :null => false
    t.string :email, :null => false
    t.string :password
    t.integer :login_count, :null => false, :default => 0
    t.boolean :is_active, :null => false, :default => true
    t.timestamps
 end
end
Foreign Key Constraints
Do you use foreign key constraints or not?

      • Rails discourages foreign keys
      • Rails promotes enforcement of data integrity
        via the model (with validations)
      • Rails defines model relationships (with
        associations)


      Do you need foreign keys?
                My answer: It depends….
Think of your database
           as a source of water.




                       If your app is a…
…Walled Fortress, with a well in the central
 courtyard that can only be accessed
 through controlled means – then
  you don’t need foreign keys
…Wildlife Preserve, with a pond that
 serves as a watering hole for all sorts of
 animals – then you need foreign keys
Foreign Key Helper Code
module MigrationHelpers
 def fk(from_table, from_column, to_table)
  execute “alter table #{from_table}
          add constraint #{constraint(from_table, from_column)}
          foreign key (#{from_column}) references #{to_table}(id)”
 end

 def drop_fk(from_table, from_column)
  execute “alter table #{from_table}
        drop foreign key #{constraint(from_table, from_column)}”
 end

 def constraint(table, column)
  "fk_#{table}_#{column}"
 end
end
Conditional Logic in Migrations
Migrations are Ruby. You can do anything in Ruby...

   •   Find out what database is in use:
       Rails 2.3.x
       adapter = User.connection.instance_variable_get("@config")[:adapter]
       Rails 3.x
       adapter = connection.adapter_name.downcase.to_sym

   •   Find out what environment is in use:
       if RAILS_ENV == ‘production’ …       # Rails 2.3.x
       if Rails.env == :production …        # Rails 3.x

   Especially useful if environments are different, e.g. – your laptop
   dev environment uses MySQL, but production uses Oracle
Fixture Recommendations
Fixtures are nice, but problematic.


       • Can use fixtures for “lookup” data – e.g.
         states, countries, etc.
       • Reference in both migrations and tests
       • Also consider seeds for data
       • For dynamic test data, use tools like
         FactoryGirl or Machinist
Loading a Fixture in a Migration
require 'active_record/fixtures’

class CreateCountries < ActiveRecord::Migration
  def self.up
   create_table :countries do |t|
   end

  Fixtures.create_fixtures('test/fixtures', File.basename("countries.yml", '.*'))
 end

 def self.down
   drop_table :countries
 end
end
Delegation
• Old-style convenience method to pull data
  from other models
   # In the User model…             Does user have a profile?
   def birthday                     Is caller aware of DB call?
      self.profile.birthday
   end


• New-style using delegation

   # In the User model…
   delegate :birthday, :to => :profile
Limit what you bring back with find
 - Use the will_paginate gem
 - Or use limits: User.limit(5)         # Rails 3.x
                  User.all(:limit => 5) # Rails 2.3.
Don’t create methods with
the same name as associations –
BAD IDEA
Conclusion
• Harness the power of Rails
  - But understand what it’s doing for you
• Minimize database calls, but don’t go crazy
  - Try eager loading in your find statements
• The console is your friend…use it…
• Consider data integrity in your apps
  - Or somebody will pay the price later
• Test, test, test
  - Try RSpec, Factory Girl and SimpleCov, etc.

Contenu connexe

Tendances

Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2Maksym Tolstik
 
You Used To Inject Me In Your Constructor
 You Used To Inject Me In Your Constructor You Used To Inject Me In Your Constructor
You Used To Inject Me In Your ConstructorVeronica Lillie
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapJoost de Vries
 
Introduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingIntroduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingBlessing Ebowe
 

Tendances (9)

Akka framework
Akka frameworkAkka framework
Akka framework
 
Akka - A Brief Intro
Akka - A Brief IntroAkka - A Brief Intro
Akka - A Brief Intro
 
Part 2 Python
Part 2 PythonPart 2 Python
Part 2 Python
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
PresentationPatterns_v2
PresentationPatterns_v2PresentationPatterns_v2
PresentationPatterns_v2
 
You Used To Inject Me In Your Constructor
 You Used To Inject Me In Your Constructor You Used To Inject Me In Your Constructor
You Used To Inject Me In Your Constructor
 
Effect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmapEffect systems in scala: beyond flatmap
Effect systems in scala: beyond flatmap
 
Introduction to React by Ebowe Blessing
Introduction to React by Ebowe BlessingIntroduction to React by Ebowe Blessing
Introduction to React by Ebowe Blessing
 
Introduction to the Actor Model
Introduction to the Actor ModelIntroduction to the Actor Model
Introduction to the Actor Model
 

En vedette

Louise d - trial presentation
Louise d - trial presentationLouise d - trial presentation
Louise d - trial presentationTrailplan
 
Early release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumEarly release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumJennifer Marten
 
MedicinMan June 2012 Issue
MedicinMan June  2012 IssueMedicinMan June  2012 Issue
MedicinMan June 2012 IssueAnup Soans
 
MedicinMan December 2011
MedicinMan December 2011MedicinMan December 2011
MedicinMan December 2011Anup Soans
 
Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012fabricandoweb
 
Content area read alouds
Content area read aloudsContent area read alouds
Content area read aloudsS Bryce Kozla
 
Penerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiPenerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiBahtera
 
Dafo came safa urgel pii
Dafo   came safa urgel piiDafo   came safa urgel pii
Dafo came safa urgel piiFernando Guadix
 
Accelerate Journey To The Cloud
Accelerate Journey To The CloudAccelerate Journey To The Cloud
Accelerate Journey To The CloudMark Treweeke
 
Supplier or Partner
Supplier or PartnerSupplier or Partner
Supplier or Partnerjimholc385
 
Individual sections development exercise #5
Individual sections development exercise #5Individual sections development exercise #5
Individual sections development exercise #5tykl94
 

En vedette (20)

RPforEUH2031
RPforEUH2031RPforEUH2031
RPforEUH2031
 
Louise d - trial presentation
Louise d - trial presentationLouise d - trial presentation
Louise d - trial presentation
 
Best of The Talking Village Blog
Best of The Talking Village BlogBest of The Talking Village Blog
Best of The Talking Village Blog
 
Early release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculumEarly release october 2014 engagement & curriculum
Early release october 2014 engagement & curriculum
 
Hot Air Hand Tools
Hot Air Hand ToolsHot Air Hand Tools
Hot Air Hand Tools
 
MedicinMan June 2012 Issue
MedicinMan June  2012 IssueMedicinMan June  2012 Issue
MedicinMan June 2012 Issue
 
Vendere con motori di ricerca e social network. Olos27102011
Vendere con motori di ricerca e social network. Olos27102011Vendere con motori di ricerca e social network. Olos27102011
Vendere con motori di ricerca e social network. Olos27102011
 
MedicinMan December 2011
MedicinMan December 2011MedicinMan December 2011
MedicinMan December 2011
 
Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012Pesquisa Ibope Alvorada FM Março de 2012
Pesquisa Ibope Alvorada FM Março de 2012
 
Content area read alouds
Content area read aloudsContent area read alouds
Content area read alouds
 
Penerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi InformasiPenerjemahan Teks Teknologi Informasi
Penerjemahan Teks Teknologi Informasi
 
One 2 One Rollover
One 2 One RolloverOne 2 One Rollover
One 2 One Rollover
 
Dafo came safa urgel pii
Dafo   came safa urgel piiDafo   came safa urgel pii
Dafo came safa urgel pii
 
Tobacco Cessation: Accept The Challenge
Tobacco Cessation: Accept The ChallengeTobacco Cessation: Accept The Challenge
Tobacco Cessation: Accept The Challenge
 
CQ Associates v8
CQ Associates v8CQ Associates v8
CQ Associates v8
 
Magico
MagicoMagico
Magico
 
P kzach
P kzachP kzach
P kzach
 
Accelerate Journey To The Cloud
Accelerate Journey To The CloudAccelerate Journey To The Cloud
Accelerate Journey To The Cloud
 
Supplier or Partner
Supplier or PartnerSupplier or Partner
Supplier or Partner
 
Individual sections development exercise #5
Individual sections development exercise #5Individual sections development exercise #5
Individual sections development exercise #5
 

Similaire à Rails Tips and Best Practices

Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementLaurent Leturgez
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...InfluxData
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesMats Kindahl
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World DominationcPanel
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersMichael Rys
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on RailsAvi Kedar
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Jan Helke
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Yasuko Ohba
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performanceEngine Yard
 
Building an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowBuilding an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowDatabricks
 

Similaire à Rails Tips and Best Practices (20)

Python and Oracle : allies for best of data management
Python and Oracle : allies for best of data managementPython and Oracle : allies for best of data management
Python and Oracle : allies for best of data management
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
Michael Hall [InfluxData] | Become an InfluxDB Pro in 20 Minutes | InfluxDays...
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL Databases
 
Rails israel 2013
Rails israel 2013Rails israel 2013
Rails israel 2013
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Rails Security
Rails SecurityRails Security
Rails Security
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
U-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for DevelopersU-SQL - Azure Data Lake Analytics for Developers
U-SQL - Azure Data Lake Analytics for Developers
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Building an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflowBuilding an ML Platform with Ray and MLflow
Building an ML Platform with Ray and MLflow
 

Plus de David Keener

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight ScenesDavid Keener
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space BattleDavid Keener
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive SettingDavid Keener
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for WritersDavid Keener
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century WriterDavid Keener
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten PassengersDavid Keener
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!David Keener
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineDavid Keener
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business ModelsDavid Keener
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook AppsDavid Keener
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsDavid Keener
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffoldDavid Keener
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsDavid Keener
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On RailsDavid Keener
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyDavid Keener
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteDavid Keener
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartDavid Keener
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: RailsDavid Keener
 

Plus de David Keener (20)

Writing Killer Fight Scenes
Writing Killer Fight ScenesWriting Killer Fight Scenes
Writing Killer Fight Scenes
 
Build a Space Battle
Build a Space BattleBuild a Space Battle
Build a Space Battle
 
Creating an Adaptive Setting
Creating an Adaptive SettingCreating an Adaptive Setting
Creating an Adaptive Setting
 
Public Speaking for Writers
Public Speaking for WritersPublic Speaking for Writers
Public Speaking for Writers
 
21st Century Writer
21st Century Writer21st Century Writer
21st Century Writer
 
Titanic: The Forgotten Passengers
Titanic: The Forgotten PassengersTitanic: The Forgotten Passengers
Titanic: The Forgotten Passengers
 
Elevator Up, Please!
Elevator Up, Please!Elevator Up, Please!
Elevator Up, Please!
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
Killer Business Models
Killer Business ModelsKiller Business Models
Killer Business Models
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Building Facebook Apps
Building Facebook AppsBuilding Facebook Apps
Building Facebook Apps
 
Leveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook AppsLeveraging Rails to Build Facebook Apps
Leveraging Rails to Build Facebook Apps
 
Quick Start: ActiveScaffold
Quick Start: ActiveScaffoldQuick Start: ActiveScaffold
Quick Start: ActiveScaffold
 
Creating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector GraphicsCreating Custom Charts With Ruby Vector Graphics
Creating Custom Charts With Ruby Vector Graphics
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
 
Using Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case StudyUsing Rails to Create an Enterprise App: A Real-Life Case Study
Using Rails to Create an Enterprise App: A Real-Life Case Study
 
Practical JRuby
Practical JRubyPractical JRuby
Practical JRuby
 
Implementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking SiteImplementing OpenID for Your Social Networking Site
Implementing OpenID for Your Social Networking Site
 
Creating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChartCreating Dynamic Charts With JFreeChart
Creating Dynamic Charts With JFreeChart
 
Quick Start: Rails
Quick Start: RailsQuick Start: Rails
Quick Start: Rails
 

Dernier

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#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
 
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
 

Dernier (20)

WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#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
 
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
 

Rails Tips and Best Practices

  • 1. Rails Tips and Best Practices By David Keener http://www.keenertech.com Version 1.1 - April 28, 2012
  • 2. Introduction Ruby on Rails is an exciting technology…a well- crafted framework with innovative philosophies baked in to facilitate Agile Web Development • But even so, there are pitfalls… • A few simple tips can help you avoid • the most common pitfalls
  • 3. The Log File is Your Friend You can’t optimize if you don’t know what your code is doing -- leverage the log file…. • Beginning Rails developers write inefficient code - Log File: /log/development.log • Shows all web page parameters - Posted Fields - URL Parameters • Shows all executed SQL
  • 4. A Sample Log File Processing LoginController#index (for 127.0.0.1 at 2009-08-27 03:33:44) [POST] Parameters: {"x"=>"25", "y"=>"10”, "authenticity_token"=>"bVOEM1qk1F4AH0=", "login_name"=>"dkeener@keenertech.com", "password"=>”sample"} [4;36;1mUser Columns (2.5ms)[0m [0;1mSHOW FIELDS FROM `users`[0m [4;35;1mUser Load (40.8ms)[0m [0mSELECT * FROM `users` WHERE (`users`.`password` = ’gHyfrds76jD' AND `users`.`email` = 'dkeener@keenertech.com') LIMIT 1[0m [4;36;1mProfile Columns (2.1ms)[0m [0;1mSHOW FIELDS FROM `profiles`[0m [4;35;1mProfile Load (1.2ms)[0m [0mSELECT * FROM `profiles` WHERE (`profiles`.`user_id` = 3) LIMIT 1[0m [4;36;1mUser Update (0.3ms)[0m [0;1mUPDATE `users` SET `login_count` = 4, `updated_at` = '2009-08-27 07:33:45' WHERE `id` = 3[0m Redirected to http://127.0.0.1:3000/ Completed in 624ms (DB: 48) | 302 Found [http://127.0.0.1/login]
  • 5. My Program Blew Up on a Query “I was doing a find(45) and my code blew up!” • find(#) raises a RecordNotFound exception if it doesn’t find a matching row • But find_by_id(#) returns nil if not found • And the first, all and last methods return nil if they fail It’s easy to forget about this…
  • 6. Column Definitions Rails makes building your database easy… rails generate model User first_name:string last_name:string login_name:string password:string • Defaults to NULL-able columns - If it’s required, it should be NOT NULL • Strings => varchar(255) - Why worry about storage? Just use the default size - Let model validations handle size constraints (if any)
  • 7. A Typical Migration (Excerpt) def self.up create_table :users do |t| t.string :first_name, :null => false t.string :last_name, :null => false t.string :login_name, :null => false t.string :email, :null => false t.string :password t.integer :login_count, :null => false, :default => 0 t.boolean :is_active, :null => false, :default => true t.timestamps end end
  • 8. Foreign Key Constraints Do you use foreign key constraints or not? • Rails discourages foreign keys • Rails promotes enforcement of data integrity via the model (with validations) • Rails defines model relationships (with associations) Do you need foreign keys? My answer: It depends….
  • 9. Think of your database as a source of water. If your app is a…
  • 10. …Walled Fortress, with a well in the central courtyard that can only be accessed through controlled means – then you don’t need foreign keys
  • 11. …Wildlife Preserve, with a pond that serves as a watering hole for all sorts of animals – then you need foreign keys
  • 12. Foreign Key Helper Code module MigrationHelpers def fk(from_table, from_column, to_table) execute “alter table #{from_table} add constraint #{constraint(from_table, from_column)} foreign key (#{from_column}) references #{to_table}(id)” end def drop_fk(from_table, from_column) execute “alter table #{from_table} drop foreign key #{constraint(from_table, from_column)}” end def constraint(table, column) "fk_#{table}_#{column}" end end
  • 13. Conditional Logic in Migrations Migrations are Ruby. You can do anything in Ruby... • Find out what database is in use: Rails 2.3.x adapter = User.connection.instance_variable_get("@config")[:adapter] Rails 3.x adapter = connection.adapter_name.downcase.to_sym • Find out what environment is in use: if RAILS_ENV == ‘production’ … # Rails 2.3.x if Rails.env == :production … # Rails 3.x Especially useful if environments are different, e.g. – your laptop dev environment uses MySQL, but production uses Oracle
  • 14. Fixture Recommendations Fixtures are nice, but problematic. • Can use fixtures for “lookup” data – e.g. states, countries, etc. • Reference in both migrations and tests • Also consider seeds for data • For dynamic test data, use tools like FactoryGirl or Machinist
  • 15. Loading a Fixture in a Migration require 'active_record/fixtures’ class CreateCountries < ActiveRecord::Migration def self.up create_table :countries do |t| end Fixtures.create_fixtures('test/fixtures', File.basename("countries.yml", '.*')) end def self.down drop_table :countries end end
  • 16. Delegation • Old-style convenience method to pull data from other models # In the User model… Does user have a profile? def birthday Is caller aware of DB call? self.profile.birthday end • New-style using delegation # In the User model… delegate :birthday, :to => :profile
  • 17. Limit what you bring back with find - Use the will_paginate gem - Or use limits: User.limit(5) # Rails 3.x User.all(:limit => 5) # Rails 2.3.
  • 18. Don’t create methods with the same name as associations – BAD IDEA
  • 19. Conclusion • Harness the power of Rails - But understand what it’s doing for you • Minimize database calls, but don’t go crazy - Try eager loading in your find statements • The console is your friend…use it… • Consider data integrity in your apps - Or somebody will pay the price later • Test, test, test - Try RSpec, Factory Girl and SimpleCov, etc.