SlideShare a Scribd company logo
Basic Rails Training
Arthit Hongchintakul
Swiftlet Co., Ltd.
contact@swiftlet.co.th
Introduction to Ruby on Rails
> Ruby: Dynamically but strongly typed OO language.
> Rails: Web application framework built on Ruby.
> Web application = HTTP communication
> Rails is designed upon the MVC pattern.
> Ruby libraries are packaged and distributed as Rubygems
> Rubygems you MUST know: rails, bundler, rake
Setting up your machine
> Either native Ubuntu machine, or an Ubuntu virtual machine.
> For Ubunbu VM, the host machine needs 8+ GB Ram, decent
graphics adapter, and more than 32 GB free space dedicated
to the VM. Virtualbox.org offers free virtualization software.
> “Stable” releases are recommended for Ubuntu. Currently
12.04 is the latest stable. Use 64-bit desktop version.
> Follow instructions here to install required packages.
Revenue Science Specifics
> Use Ruby 1.9 series
> Use Rails 3.2 series
> Use Postgres database
> For today’s class, use sqlite
> Set up github and Heroku accounts. We’ll use this later
> Exercise: if you haven’t done so already, setup your machine.
Introduction to Ruby
> Hello World program
> Ruby Syntax Ruby on Rails.pdf
> OOP in A PIE
> Modules
> Closures
> Enumerables
HTTP Refresher
> HTTP
> Client-Server architecture
> Stateless architecture
> HTTP Request
> HTTP Response
> REST
MVCServer
InternetRequest
Controller
Request
Model
Model
Model
Model
DB
Response Response
View
Rails Application in 7 steps
$ rails new five_minute
$ cd five_minute
$ echo “gem ”therubyracer”” >> Gemfile
$ bundle install
$ rails generate scaffold post title:string body:text
$ rake db:migrate
$ rails s
$ firefox http://localhost:3000/posts
Rails Request Lifecycle
> Routing
> Controller
– Action
> Model
> View
– Embedded Ruby
Rake
> Ruby’s “make”
> Task management
> Rake tasks you must know today:
– rake db:drop --trace
– rake db:create
– rake db:migrate
> rake -T
Exercise: Due next class
Create a new Rails application that reads and check Sudoku
answers. Using the generator, create a scaffold and modify it to
perform the following:
> List previously submitted Sudoku answers, also show that the
answer is correct or not
> Show the detail of a record of Sudoku answer. Show that the
answer is correct or not
> A form to create a new Sudoku answer record
Exercise: Due next class
> New form submission should create a record in the database,
and then redirect to the index page
> Edit form of the Sudoku answer
> Edit form submission should update an existing record in the
database and then redirect to the show page
> Delete a Sudoku answer record
> Extra credit: create another scaffold to generate a correct grid
Sudoku correctness
> A correct Sudoku answer must be a grid of 9 columns and 9 rows
> Every cell in the answer must contain one of the digits 1-9
> Every column of the answer must contain all digits 1-9
> Every row of the answer must contain all digits 1-9
> Partition the main grid to a subset of 3x3 grid, each sub-grid must
contain all digits 1-9
> This implies that there is no repetition in the columns, rows, and
sub-grid
Agenda
> Revenue Science’s Rails
> Git, github
> Heroku
> Deployment process
> Rails Model
> Rails Controller
> Rails View
Setting up Revenue Science Machine
$ rvm install 1.9.3-p545
$ rvm use 1.9.3-p545@revenue_science --create --default
$ gem install rails --version “3.2.17”
Git
> Git is a distributed version control system
> Version control system: save points and history of software
development
> Distributed VCS vs. Centralized VCS
> No one authoritative source
Github
> https://github.com
> Sign up for your own account.
> You will need to pay for a private repository.
> Consider https://bitbucket.org for a service with free private
repositories.
> Create a key pair to connect with github
ssh-keygen
> Remote access without typing your password
> Create a key pair with the command ssh-keygen
> 2 keys are generated: id_rsa and id_rsa.pub
– You can set the key name.
> id_rsa is a private key. Keep it to yourself.
> id_rsa.pub is a public key. Share this key to anyone you need
to communicate with. In this case, github.
> Visit https://github.com/settings/ssh to add your public key
~/.ssh
> This is where you keep your private keys
> This is where you keep your ssh config file
$ mkdir –p0700 ~/.ssh
$ cp id_rsa ~/.ssh/
$ touch ~/.ssh/config
$ chmod 0600 ~/.ssh/config
~/.ssh/config
Host github.com
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa
> Test by running the command
$ ssh -vT github.com
> It should greet you with your username
Hi arthith! You've successfully authenticated, but
GitHub does not provide shell access.
Creating a new repository
Server side
> Create a new, empty one.
> Fork an existing repository.
Local machine side
> Initialize your repository
> Add a commit
> Add a remote repository
> Push your code to the remote repository
> Clone it to another machine
Basic git workflow
> Pull remote changes
> Make your own change
> Test your change; make sure everything works
> git status
> git diff to see the change; make sure no unintentional change exists
> git add to stage the change
> git rm, git mv to remove or move files
> git reset HEAD /path/to/file to un-stage changes
> git commit –m “commit message” –m “another message”
> git pull –rebase
> git push
> Start over.
Merge conflict
> Resolve the conflict in the file, choose yours or remote code,
or merge the two together.
> git add the files
> git rebase --continue # to apply the merge
> git rebase --abort # to abort pulling
> git reset --hard <commit id> # revert to commit with id
> Git pull to get fresh remote
Feature branching
> A discipline to manage software releases
> Every new feature should be developed on its own branch
> When a feature is accepted, the branch is merged on to the
master branch via pull request
> Your manager will test the branch and eventually merge the
code to master
> Be very careful of merge conflict. Be prepared to help your
manager merge your change in the case of conflict.
Git branching
$ git branch –a
$ git branch new_branch
$ git checkout new_branch
$ git push –u origin new_branch
$ git checkout master
$ git merge new_branch
$ git push
Heroku
> Cloud-base zero-configuration web application hosting service
> Solves the problem of complicated steps to deploy Rails application.
> All you need is a git repository of your Rails application and Heroku
Toolbelt application.
> ssh key is also required. Use a different key for each service.
Deploy to Heroku
Install https://toolbelt.heroku.com
heroku git:remote –a app-name-here #OR
heroku apps:create app-name-here
heroku addons:add heroku-postgresql
# heroku addons:docs heroku-postgresql
Remove sqlite from Gemfile
Use gem “pg” instead
Modify database.yml to use postgresql in development
Deploy to Heroku
RAILS_ENV=development rake assets:precompile
git add .
git commit –m “precompile assets”
git push origin master
git push heroku master
heroku run “RAILS_ENV=production rake db:setup” #OR
# heroku run “RAILS_ENV=production rake db:migrate”
heroku logs –t # to see the logs
Now try and deploy your application to heroku
Rails routing
> Routing
– RESTful resource: 7 basic routes and their convention
– Custom RESTful routes: member vs collection
– Non-REST routes: custom route mapping
> Mapping to controllers#actions
$ rake routes
Controller
> Controller Action
> Non-action methods AKA helper methods
> Action filters
> Multiple formats
> Rendering
> Redirection
> HTTP Error Codes
Rails Migration
> Why migration?
> Creating a new migration
> #change vs #up and #down
> IrreversibleMigration error
> schema.rb
$ rails generate migration add_description
…
$ rake db:migrate
$ rake db:rollback
$ rake db:reset
$ rake db:drop db:create db:migrate
$ rake db:schema:load
$ rake db:test:prepare
$ rake db:seed
Model
> ORM: Object Relational Mapping
> Entity Definition – migration
> Relationship Definition
– inverse_of
> Validation
> Callbacks
> Transaction: ACID Property
> Scopes : Decorator Pattern
> Non-ORM models
View
> ERB
> Layout
> Partial
> Partial’s local variables
> Object partial
> Collection partial
> Asset Pipeline
Asset Pipeline
> DRY
> Scoping
> Caching
– rake assets:precompile
– rake assets:clean
Exercise
> Create a new contact list application
> Push to github repository
> Deploy to Heroku
> Create a new feature branch
> Add “Company” feature
– Contact belongs to a company
– Company has many contacts
> Pull request
> Merge feature
> Deploy
Test Driven Development
Red Ball
Green
Ball
Refactor
Software Quality
> Correctness
> Optimal
– Sufficiency
– Necessity
Rails Application Design
Model
Entity
Relationship
Validation
Indexing
Optimization
Behavior
Controller
Routing
Actions (Index, show, new, create, edit, update,
destroy)
Custom actions
Filters
Request Parameters
Authentication
Authorization
Response
View
Layout
Navigation
Structure
Content
Representation
Design
Behavior
Rails Testing Tools
> Rspec-rails
> Capybara
> Capybara-screenshot
> Capybara-webkit
> Shoulda-matcher
Anatomy of a test case
> Acceptance criteria
– Given [a certain circumstance]
– When [an action is performed]
– Then [an expected behavior should occur]
> Test case
– Setup (Given)
– Perform (When)
– Assert (Then)
Level of testing
> Unit
> Functional
> Integration
> Acceptance
QA Process
> Requirement analysis
> Test scenario verification
> Try to break the feature
> File bug report
Bug Report
> Refer to the requirement
> State what is wrong
> Steps to reproduce
> State what the expected behavior is
> Developers:
– Verify the bug: requirement from another work, missing
requirement, external error, software error
– Reproduce the bug
– Fix it
Service Layer
Servers talking to each other
Service Layer
> Essentially still HTTP
> Request header
> Controller Actions
> Response header and body
> Sessions
> Integration testing
> Non-integration testing
Receiving Service Calls
> HTTPS is (usually) handled by the reverse-proxy
> Rails accept various format of request parameters
– HTML Form parameters
– JSON
– XML parameters requires actionpack-xml_parser gem
> Rails auto-convert the parameters to params hash.
> Same MVC pattern.
> Response format depends on the request “accept” header
> Consistent Service API specifications
> API specification may be required for remote end point developers.
> rspec –fd with well written specs
Rendering Response
> Response code is very important
> JSON
– Object#to_json method
– JSON.pretty_generate(object)
– Builder view template
> XML
– ActiveRecord::Base#to_xml method
– Nokogiri gem
– XML view template
– Builder view template
> Others
Sending Service Calls
> Various methods, but essentially all HTTP/HTTPS
> Ruby ‘net/http’
> rest-client gem
> Generate acceptable request parameters
> Handle responses gracefully, including error responses
> Timing out at different stages: open, read, SSL, continue
> Remote API specifications
Separation of Responsibility
> Service call can be implemented in a separated model
> Service model can be separated into the application logic and
the connection driver.
> Application logic provides higher level of functionality to the
application.
> Drivers handles all the remote connection and payload
management.
> Drivers are interchangeable for API version updates.
SOAP
> Another layer of communication on top of HTTP
– May also be on top of other application layer such as SMTP
> SOAP message consists of an envelope, and the body
> Instead of specifying RESTful URL, SOAP goes to a specific URL,
the SOAP service URL. This breaks down MVC quite badly in Rails.
> In the message SOAP will say what action is requested and what
parameters are sent.
> SOAP response looks the same as SOAP request.
> Crazy XML all the way through
> savon gem
Sessions
> HTTP is stateless
> Sessions can be implemented in Rails
> Service call is almost always atomic
> If it’s not atomic, you’re doing it wrong
> Service controllers should not rely on session for any
information.
> Authentication are to be implemented with encryption and
message signing
Security 101
> Authentication
– Verification of identity: you are who you say you are
– Prevent: false identity, eavesdropping
> Authorization
– Verification of right: you can do what you are trying to do
– Prevent: access violation, unauthorized action, e.g., self-promotion to site
admin
– No read up, no write down
> Auditing
– Verification of action: a record of what you have done
– Record of who did what, changed what to what, at what time, what server
Integration Testing
Development
Test instance
Remote test
instance
Integration Testing
> Testing receiving calls is simply controller tests.
> Testing sending calls requires a test instance of remote end point
> Setup has to be done on both remote and local sides
> Perform step hits the remote end point
> Assertion may be verified on the local or remote side, usually
local.
> The hard part are setting up and testing the error cases
> The hardest part is testing the network error handling
Non-Integration Testing
Local
connection
driver
Mock/Stubs
Non-Integration Testing
> Somewhat reduce the complexity in setting up
> Separation of the remote and local endpoints
> Mocking is required to provide remote responses
> Mocking must strictly conform to remote API specification
> Discipline must be taken seriously to never mock internal system
> Only mock what you cannot access or control
> Very high risk of systems being out of sync if remote end point is still under
development
> Can easily test error cases, timing out, and network errors
> Testing code that requires service call may be stubbed for reasonable
complexity
> Mock vs Stubs
Background Worker
Background Worker
> Reasonable response time for a web application is 7 seconds
> Push long, complex tasks to background workers
> Background workers imply infrastructure and code complexity
> Introduction to distributed system
Background Worker
PGSQL
Message
Queue
App
Server
App
Server
App
Server
App
Server
Background
Worker
Background
Worker
Background
Worker
Background
Worker
Task
Background Worker
> Usually needs domain model knowledge and logic
– Relationship, validations
– Custom logic
> Needs to communicate with the database
> Might as well use Rails environment
> resque gem
Background worker gems
> https://github.com/blog/542-introducing-resque
> https://github.com/resque/resque
> Resque comes with a whole lot of plugins
– http://rubygems.org/search?utf8=%E2%9C%93&query=resque
– resque-scheduler, resque-retry, resque-mailer
> Front end interface with a bunch of nice features
– Status, re-queue, cancel job, etc.
Redis
> Key-Value storage, much like persistent JSON hash
> Has a lot of traits that represent messaging queue
> Ridiculously fast; written in pure C.
> Redis earns the inventor a job at VMWare
> Redis has its own set of syntax:
– http://redis.io/commands
> redis, redis-namespace gems provide Ruby API
– https://github.com/redis/redis-rb
– https://github.com/resque/redis-namespace
Infrastructure Setup
> Resque server(s)
> Redis database
– Fault tolerance
> Deployment steps
> System monitoring: redis, resque parent, resque workers
> Testing environment
– Job test is a simple unit test
– Functional test that connects to test Redis instance
– Be careful when testing email functionality
Where does it go wrong?
> Resque front end
> Job functionality
> Resque server inspection
– ps afx
– lsof –Pni
– QUEUE=queue-name rake resque:work
> Redis server
– redis command line interface
– Redundancy

More Related Content

PDF
手把手教你如何串接 Log 到各種網路服務
Mu Chun Wang
 
PDF
Ship your Scala code often and easy with Docker
Marcus Lönnberg
 
PPTX
Vagrant introduction for Developers
Antons Kranga
 
PDF
Heroku 101 py con 2015 - David Gouldin
Heroku
 
KEY
Matt Gauger - Git & Github web414 December 2010
Matt Gauger
 
PDF
The JavaFX Ecosystem
Andres Almiray
 
PPTX
DevOps Hackathon - Session 1: Vagrant
Antons Kranga
 
PDF
Docker and Puppet for Continuous Integration
Giacomo Vacca
 
手把手教你如何串接 Log 到各種網路服務
Mu Chun Wang
 
Ship your Scala code often and easy with Docker
Marcus Lönnberg
 
Vagrant introduction for Developers
Antons Kranga
 
Heroku 101 py con 2015 - David Gouldin
Heroku
 
Matt Gauger - Git & Github web414 December 2010
Matt Gauger
 
The JavaFX Ecosystem
Andres Almiray
 
DevOps Hackathon - Session 1: Vagrant
Antons Kranga
 
Docker and Puppet for Continuous Integration
Giacomo Vacca
 

What's hot (20)

PDF
Making the Most of Your Gradle Build
Andres Almiray
 
PDF
BOSH / CF Deployment in modern ways #cf_tokyo
Toshiaki Maki
 
PDF
Making the Most of Your Gradle Build
Andres Almiray
 
PDF
Kube Your Enthusiasm - Tyler Britten
VMware Tanzu
 
PPTX
GIT in a nutshell
alignan
 
PDF
Spring Booted, But... @JCConf 16', Taiwan
Pei-Tang Huang
 
PDF
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
DynamicInfraDays
 
PDF
Docker for (Java) Developers
Rafael Benevides
 
PDF
Containerizing a Web Application with Vue.js and Java
Jadson Santos
 
PDF
Spring Into Kubernetes DFW
VMware Tanzu
 
PPTX
Get started with docker &amp; dev ops
Asya Dudnik
 
PPTX
DevOps hackathon Session 2: Basics of Chef
Antons Kranga
 
PPTX
GIT, RVM, FIRST HEROKU APP
Pavel Tyk
 
PDF
Puppet Performance Profiling
ripienaar
 
PPTX
Get started with docker &amp; dev ops
Asya Dudnik
 
PDF
HotPush with Ionic 2 and CodePush
Evan Schultz
 
PPT
Python virtualenv & pip in 90 minutes
Larry Cai
 
PPTX
Gruntwork Executive Summary
Yevgeniy Brikman
 
PPTX
Laravel Beginners Tutorial 2
Vikas Chauhan
 
PDF
Deep drive into Nova
Udayendu Kar
 
Making the Most of Your Gradle Build
Andres Almiray
 
BOSH / CF Deployment in modern ways #cf_tokyo
Toshiaki Maki
 
Making the Most of Your Gradle Build
Andres Almiray
 
Kube Your Enthusiasm - Tyler Britten
VMware Tanzu
 
GIT in a nutshell
alignan
 
Spring Booted, But... @JCConf 16', Taiwan
Pei-Tang Huang
 
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
DynamicInfraDays
 
Docker for (Java) Developers
Rafael Benevides
 
Containerizing a Web Application with Vue.js and Java
Jadson Santos
 
Spring Into Kubernetes DFW
VMware Tanzu
 
Get started with docker &amp; dev ops
Asya Dudnik
 
DevOps hackathon Session 2: Basics of Chef
Antons Kranga
 
GIT, RVM, FIRST HEROKU APP
Pavel Tyk
 
Puppet Performance Profiling
ripienaar
 
Get started with docker &amp; dev ops
Asya Dudnik
 
HotPush with Ionic 2 and CodePush
Evan Schultz
 
Python virtualenv & pip in 90 minutes
Larry Cai
 
Gruntwork Executive Summary
Yevgeniy Brikman
 
Laravel Beginners Tutorial 2
Vikas Chauhan
 
Deep drive into Nova
Udayendu Kar
 
Ad

Viewers also liked (9)

PDF
Design Pattern From Java To Ruby
yelogic
 
PDF
エクストリームエンジニア1
T-arts
 
ODP
デザインパターン(初歩的な7パターン)
和明 斎藤
 
PPTX
Design Patterns in Ruby
Mindfire Solutions
 
ODP
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
tomo_masakura
 
PPT
Firefox-Addons
Mindfire Solutions
 
PPT
Metaprogramming With Ruby
Farooq Ali
 
PDF
The way to the timeless way of programming
Shintaro Kakutani
 
PDF
Functional Ruby
Amoniac OÜ
 
Design Pattern From Java To Ruby
yelogic
 
エクストリームエンジニア1
T-arts
 
デザインパターン(初歩的な7パターン)
和明 斎藤
 
Design Patterns in Ruby
Mindfire Solutions
 
Strategy パターンと開放/閉鎖原則に見るデザインパターンの有用性
tomo_masakura
 
Firefox-Addons
Mindfire Solutions
 
Metaprogramming With Ruby
Farooq Ali
 
The way to the timeless way of programming
Shintaro Kakutani
 
Functional Ruby
Amoniac OÜ
 
Ad

Similar to Basic Rails Training (20)

PPT
Continuos integration for iOS projects
Aleksandra Gavrilovska
 
PDF
Panmind at Ruby Social Club Milano
Panmind
 
KEY
groovy & grails - lecture 9
Alexandre Masselot
 
KEY
Supa fast Ruby + Rails
Jean-Baptiste Feldis
 
PDF
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
Leo Lorieri
 
PDF
Gitlab ci, cncf.sk
Juraj Hantak
 
PPT
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Srijan Technologies
 
PDF
Automate Your Automation | DrupalCon Vienna
Pantheon
 
PPT
Rails Rookies Bootcamp - Blogger
Nathanial McConnell
 
PDF
How we maintain 200+ Drupal sites in Georgetown University
Ovadiah Myrgorod
 
KEY
Mojolicious - A new hope
Marcus Ramberg
 
PDF
Jazoon12 355 aleksandra_gavrilovska-1
Netcetera
 
PPTX
Working in Team using Git in Unity
Rifauddin Tsalitsy
 
PPTX
Toolbox of a Ruby Team
Arto Artnik
 
PDF
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
PPT
Life of a Chromium Developer
mpaproductions
 
PPTX
drupal ci cd concept cornel univercity.pptx
rukuntravel
 
PDF
Gitlab and Lingvokot
Lingvokot
 
PDF
Lean Drupal Repositories with Composer and Drush
Pantheon
 
PDF
Ruby on Rails Kickstart 101 & 102
Heng-Yi Wu
 
Continuos integration for iOS projects
Aleksandra Gavrilovska
 
Panmind at Ruby Social Club Milano
Panmind
 
groovy & grails - lecture 9
Alexandre Masselot
 
Supa fast Ruby + Rails
Jean-Baptiste Feldis
 
[EXTENDED] Ceph, Docker, Heroku Slugs, CoreOS and Deis Overview
Leo Lorieri
 
Gitlab ci, cncf.sk
Juraj Hantak
 
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Srijan Technologies
 
Automate Your Automation | DrupalCon Vienna
Pantheon
 
Rails Rookies Bootcamp - Blogger
Nathanial McConnell
 
How we maintain 200+ Drupal sites in Georgetown University
Ovadiah Myrgorod
 
Mojolicious - A new hope
Marcus Ramberg
 
Jazoon12 355 aleksandra_gavrilovska-1
Netcetera
 
Working in Team using Git in Unity
Rifauddin Tsalitsy
 
Toolbox of a Ruby Team
Arto Artnik
 
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Life of a Chromium Developer
mpaproductions
 
drupal ci cd concept cornel univercity.pptx
rukuntravel
 
Gitlab and Lingvokot
Lingvokot
 
Lean Drupal Repositories with Composer and Drush
Pantheon
 
Ruby on Rails Kickstart 101 & 102
Heng-Yi Wu
 

Recently uploaded (20)

PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Doc9.....................................
SofiaCollazos
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Doc9.....................................
SofiaCollazos
 

Basic Rails Training

  • 1. Basic Rails Training Arthit Hongchintakul Swiftlet Co., Ltd. [email protected]
  • 2. Introduction to Ruby on Rails > Ruby: Dynamically but strongly typed OO language. > Rails: Web application framework built on Ruby. > Web application = HTTP communication > Rails is designed upon the MVC pattern. > Ruby libraries are packaged and distributed as Rubygems > Rubygems you MUST know: rails, bundler, rake
  • 3. Setting up your machine > Either native Ubuntu machine, or an Ubuntu virtual machine. > For Ubunbu VM, the host machine needs 8+ GB Ram, decent graphics adapter, and more than 32 GB free space dedicated to the VM. Virtualbox.org offers free virtualization software. > “Stable” releases are recommended for Ubuntu. Currently 12.04 is the latest stable. Use 64-bit desktop version. > Follow instructions here to install required packages.
  • 4. Revenue Science Specifics > Use Ruby 1.9 series > Use Rails 3.2 series > Use Postgres database > For today’s class, use sqlite > Set up github and Heroku accounts. We’ll use this later > Exercise: if you haven’t done so already, setup your machine.
  • 5. Introduction to Ruby > Hello World program > Ruby Syntax Ruby on Rails.pdf > OOP in A PIE > Modules > Closures > Enumerables
  • 6. HTTP Refresher > HTTP > Client-Server architecture > Stateless architecture > HTTP Request > HTTP Response > REST
  • 8. Rails Application in 7 steps $ rails new five_minute $ cd five_minute $ echo “gem ”therubyracer”” >> Gemfile $ bundle install $ rails generate scaffold post title:string body:text $ rake db:migrate $ rails s $ firefox http://localhost:3000/posts
  • 9. Rails Request Lifecycle > Routing > Controller – Action > Model > View – Embedded Ruby
  • 10. Rake > Ruby’s “make” > Task management > Rake tasks you must know today: – rake db:drop --trace – rake db:create – rake db:migrate > rake -T
  • 11. Exercise: Due next class Create a new Rails application that reads and check Sudoku answers. Using the generator, create a scaffold and modify it to perform the following: > List previously submitted Sudoku answers, also show that the answer is correct or not > Show the detail of a record of Sudoku answer. Show that the answer is correct or not > A form to create a new Sudoku answer record
  • 12. Exercise: Due next class > New form submission should create a record in the database, and then redirect to the index page > Edit form of the Sudoku answer > Edit form submission should update an existing record in the database and then redirect to the show page > Delete a Sudoku answer record > Extra credit: create another scaffold to generate a correct grid
  • 13. Sudoku correctness > A correct Sudoku answer must be a grid of 9 columns and 9 rows > Every cell in the answer must contain one of the digits 1-9 > Every column of the answer must contain all digits 1-9 > Every row of the answer must contain all digits 1-9 > Partition the main grid to a subset of 3x3 grid, each sub-grid must contain all digits 1-9 > This implies that there is no repetition in the columns, rows, and sub-grid
  • 14. Agenda > Revenue Science’s Rails > Git, github > Heroku > Deployment process > Rails Model > Rails Controller > Rails View
  • 15. Setting up Revenue Science Machine $ rvm install 1.9.3-p545 $ rvm use 1.9.3-p545@revenue_science --create --default $ gem install rails --version “3.2.17”
  • 16. Git > Git is a distributed version control system > Version control system: save points and history of software development > Distributed VCS vs. Centralized VCS > No one authoritative source
  • 17. Github > https://github.com > Sign up for your own account. > You will need to pay for a private repository. > Consider https://bitbucket.org for a service with free private repositories. > Create a key pair to connect with github
  • 18. ssh-keygen > Remote access without typing your password > Create a key pair with the command ssh-keygen > 2 keys are generated: id_rsa and id_rsa.pub – You can set the key name. > id_rsa is a private key. Keep it to yourself. > id_rsa.pub is a public key. Share this key to anyone you need to communicate with. In this case, github. > Visit https://github.com/settings/ssh to add your public key
  • 19. ~/.ssh > This is where you keep your private keys > This is where you keep your ssh config file $ mkdir –p0700 ~/.ssh $ cp id_rsa ~/.ssh/ $ touch ~/.ssh/config $ chmod 0600 ~/.ssh/config
  • 20. ~/.ssh/config Host github.com Hostname github.com User git IdentityFile ~/.ssh/id_rsa > Test by running the command $ ssh -vT github.com > It should greet you with your username Hi arthith! You've successfully authenticated, but GitHub does not provide shell access.
  • 21. Creating a new repository Server side > Create a new, empty one. > Fork an existing repository. Local machine side > Initialize your repository > Add a commit > Add a remote repository > Push your code to the remote repository > Clone it to another machine
  • 22. Basic git workflow > Pull remote changes > Make your own change > Test your change; make sure everything works > git status > git diff to see the change; make sure no unintentional change exists > git add to stage the change > git rm, git mv to remove or move files > git reset HEAD /path/to/file to un-stage changes > git commit –m “commit message” –m “another message” > git pull –rebase > git push > Start over.
  • 23. Merge conflict > Resolve the conflict in the file, choose yours or remote code, or merge the two together. > git add the files > git rebase --continue # to apply the merge > git rebase --abort # to abort pulling > git reset --hard <commit id> # revert to commit with id > Git pull to get fresh remote
  • 24. Feature branching > A discipline to manage software releases > Every new feature should be developed on its own branch > When a feature is accepted, the branch is merged on to the master branch via pull request > Your manager will test the branch and eventually merge the code to master > Be very careful of merge conflict. Be prepared to help your manager merge your change in the case of conflict.
  • 25. Git branching $ git branch –a $ git branch new_branch $ git checkout new_branch $ git push –u origin new_branch $ git checkout master $ git merge new_branch $ git push
  • 26. Heroku > Cloud-base zero-configuration web application hosting service > Solves the problem of complicated steps to deploy Rails application. > All you need is a git repository of your Rails application and Heroku Toolbelt application. > ssh key is also required. Use a different key for each service.
  • 27. Deploy to Heroku Install https://toolbelt.heroku.com heroku git:remote –a app-name-here #OR heroku apps:create app-name-here heroku addons:add heroku-postgresql # heroku addons:docs heroku-postgresql Remove sqlite from Gemfile Use gem “pg” instead Modify database.yml to use postgresql in development
  • 28. Deploy to Heroku RAILS_ENV=development rake assets:precompile git add . git commit –m “precompile assets” git push origin master git push heroku master heroku run “RAILS_ENV=production rake db:setup” #OR # heroku run “RAILS_ENV=production rake db:migrate” heroku logs –t # to see the logs Now try and deploy your application to heroku
  • 29. Rails routing > Routing – RESTful resource: 7 basic routes and their convention – Custom RESTful routes: member vs collection – Non-REST routes: custom route mapping > Mapping to controllers#actions $ rake routes
  • 30. Controller > Controller Action > Non-action methods AKA helper methods > Action filters > Multiple formats > Rendering > Redirection > HTTP Error Codes
  • 31. Rails Migration > Why migration? > Creating a new migration > #change vs #up and #down > IrreversibleMigration error > schema.rb $ rails generate migration add_description … $ rake db:migrate $ rake db:rollback $ rake db:reset $ rake db:drop db:create db:migrate $ rake db:schema:load $ rake db:test:prepare $ rake db:seed
  • 32. Model > ORM: Object Relational Mapping > Entity Definition – migration > Relationship Definition – inverse_of > Validation > Callbacks > Transaction: ACID Property > Scopes : Decorator Pattern > Non-ORM models
  • 33. View > ERB > Layout > Partial > Partial’s local variables > Object partial > Collection partial > Asset Pipeline
  • 34. Asset Pipeline > DRY > Scoping > Caching – rake assets:precompile – rake assets:clean
  • 35. Exercise > Create a new contact list application > Push to github repository > Deploy to Heroku > Create a new feature branch > Add “Company” feature – Contact belongs to a company – Company has many contacts > Pull request > Merge feature > Deploy
  • 36. Test Driven Development Red Ball Green Ball Refactor
  • 37. Software Quality > Correctness > Optimal – Sufficiency – Necessity
  • 38. Rails Application Design Model Entity Relationship Validation Indexing Optimization Behavior Controller Routing Actions (Index, show, new, create, edit, update, destroy) Custom actions Filters Request Parameters Authentication Authorization Response View Layout Navigation Structure Content Representation Design Behavior
  • 39. Rails Testing Tools > Rspec-rails > Capybara > Capybara-screenshot > Capybara-webkit > Shoulda-matcher
  • 40. Anatomy of a test case > Acceptance criteria – Given [a certain circumstance] – When [an action is performed] – Then [an expected behavior should occur] > Test case – Setup (Given) – Perform (When) – Assert (Then)
  • 41. Level of testing > Unit > Functional > Integration > Acceptance
  • 42. QA Process > Requirement analysis > Test scenario verification > Try to break the feature > File bug report
  • 43. Bug Report > Refer to the requirement > State what is wrong > Steps to reproduce > State what the expected behavior is > Developers: – Verify the bug: requirement from another work, missing requirement, external error, software error – Reproduce the bug – Fix it
  • 45. Service Layer > Essentially still HTTP > Request header > Controller Actions > Response header and body > Sessions > Integration testing > Non-integration testing
  • 46. Receiving Service Calls > HTTPS is (usually) handled by the reverse-proxy > Rails accept various format of request parameters – HTML Form parameters – JSON – XML parameters requires actionpack-xml_parser gem > Rails auto-convert the parameters to params hash. > Same MVC pattern. > Response format depends on the request “accept” header > Consistent Service API specifications > API specification may be required for remote end point developers. > rspec –fd with well written specs
  • 47. Rendering Response > Response code is very important > JSON – Object#to_json method – JSON.pretty_generate(object) – Builder view template > XML – ActiveRecord::Base#to_xml method – Nokogiri gem – XML view template – Builder view template > Others
  • 48. Sending Service Calls > Various methods, but essentially all HTTP/HTTPS > Ruby ‘net/http’ > rest-client gem > Generate acceptable request parameters > Handle responses gracefully, including error responses > Timing out at different stages: open, read, SSL, continue > Remote API specifications
  • 49. Separation of Responsibility > Service call can be implemented in a separated model > Service model can be separated into the application logic and the connection driver. > Application logic provides higher level of functionality to the application. > Drivers handles all the remote connection and payload management. > Drivers are interchangeable for API version updates.
  • 50. SOAP > Another layer of communication on top of HTTP – May also be on top of other application layer such as SMTP > SOAP message consists of an envelope, and the body > Instead of specifying RESTful URL, SOAP goes to a specific URL, the SOAP service URL. This breaks down MVC quite badly in Rails. > In the message SOAP will say what action is requested and what parameters are sent. > SOAP response looks the same as SOAP request. > Crazy XML all the way through > savon gem
  • 51. Sessions > HTTP is stateless > Sessions can be implemented in Rails > Service call is almost always atomic > If it’s not atomic, you’re doing it wrong > Service controllers should not rely on session for any information. > Authentication are to be implemented with encryption and message signing
  • 52. Security 101 > Authentication – Verification of identity: you are who you say you are – Prevent: false identity, eavesdropping > Authorization – Verification of right: you can do what you are trying to do – Prevent: access violation, unauthorized action, e.g., self-promotion to site admin – No read up, no write down > Auditing – Verification of action: a record of what you have done – Record of who did what, changed what to what, at what time, what server
  • 54. Integration Testing > Testing receiving calls is simply controller tests. > Testing sending calls requires a test instance of remote end point > Setup has to be done on both remote and local sides > Perform step hits the remote end point > Assertion may be verified on the local or remote side, usually local. > The hard part are setting up and testing the error cases > The hardest part is testing the network error handling
  • 56. Non-Integration Testing > Somewhat reduce the complexity in setting up > Separation of the remote and local endpoints > Mocking is required to provide remote responses > Mocking must strictly conform to remote API specification > Discipline must be taken seriously to never mock internal system > Only mock what you cannot access or control > Very high risk of systems being out of sync if remote end point is still under development > Can easily test error cases, timing out, and network errors > Testing code that requires service call may be stubbed for reasonable complexity > Mock vs Stubs
  • 58. Background Worker > Reasonable response time for a web application is 7 seconds > Push long, complex tasks to background workers > Background workers imply infrastructure and code complexity > Introduction to distributed system
  • 60. Background Worker > Usually needs domain model knowledge and logic – Relationship, validations – Custom logic > Needs to communicate with the database > Might as well use Rails environment > resque gem
  • 61. Background worker gems > https://github.com/blog/542-introducing-resque > https://github.com/resque/resque > Resque comes with a whole lot of plugins – http://rubygems.org/search?utf8=%E2%9C%93&query=resque – resque-scheduler, resque-retry, resque-mailer > Front end interface with a bunch of nice features – Status, re-queue, cancel job, etc.
  • 62. Redis > Key-Value storage, much like persistent JSON hash > Has a lot of traits that represent messaging queue > Ridiculously fast; written in pure C. > Redis earns the inventor a job at VMWare > Redis has its own set of syntax: – http://redis.io/commands > redis, redis-namespace gems provide Ruby API – https://github.com/redis/redis-rb – https://github.com/resque/redis-namespace
  • 63. Infrastructure Setup > Resque server(s) > Redis database – Fault tolerance > Deployment steps > System monitoring: redis, resque parent, resque workers > Testing environment – Job test is a simple unit test – Functional test that connects to test Redis instance – Be careful when testing email functionality
  • 64. Where does it go wrong? > Resque front end > Job functionality > Resque server inspection – ps afx – lsof –Pni – QUEUE=queue-name rake resque:work > Redis server – redis command line interface – Redundancy