Ruby On Rails Cheat Sheet

- Developer Tools -
Ruby On Rails Cheat Sheet

What`s inside

A complete ROR cheat sheet for everyday use.
(from beginners to advanced users).

About the Content

If you are not an every day ROR  person…. or
If you forgot a syntax that you once knew … or
If you want to take a glimpse of how things are done in Ruby and on Rails … or

I think that is too many or’s already.

Introduction

  • ⇒ Created in 1995 at Japan, by Yukihiro Matsumoto (‘Matz’)
  • ⇒ High Level, General Purpose
  • ⇒ Interpreted
  • ⇒ Multi-Paradigm (Procedural, Object Oriented, Functional)
  • ⇒ Dynamically Typed

         – Variables are not declared prior to use

         – No explicit type set

  • ⇒ Dynamic Language
  • ⇒ Everything is a reference type. (No value types)
  • ⇒ Duck typing : Behaviors over types
  • ⇒ Cross platform
  • ⇒ Case sensitive with Casing Conventions

         – Classes and Constants must begin with a Capital letter.

         – Variables must start with a lowercase.

  • ⇒ Inspired by : Smalltalk, Perl, Eiffel, Ada, Basic & Lisp
  • ⇒ Ruby file extension : rb
.
  • ⇒ Thoroughly object-oriented with inheritance, mixins and metaclasses
  • ⇒ Dynamic typing and duck typing
  • ⇒ Everything is an expression (even statements)
  • ⇒ Everything is executed imperatively (even declarations)
  • ⇒ Succinct and flexible syntax
  • ⇒ Dynamic reflection and alteration of objects to facilitate metaprogramming
  • ⇒ Lexical closures, iterators and generators, with a block syntax
  • ⇒ Literal notation for arrays, hashes, regular expressions and symbols
  • ⇒ Embedding code in strings (interpolation)
  • ⇒ Default arguments
  • ⇒ Four levels of variable scope (global, class, instance, and local) denoted by sigils or the lack thereof
  • ⇒ Garbage collection
  • ⇒ First-class continuations
  • ⇒ Strict boolean coercion rules (everything is true except false and nil)
  • ⇒ Exception handling
  • ⇒ Operator overloading
  • ⇒ Built-in support for rational numbers, complex numbers and arbitrary-precision arithmetic
  • ⇒ Custom dispatch behavior (through method_missing and const_missing)
  • ⇒ Native threads and cooperative fibers
  • ⇒ Support for Unicode and multiple character encodings
  • ⇒ Native plug-in API in C
  • ⇒ Interactive Ruby Shell (a REPL)
  • ⇒ Centralized package management through RubyGems
  • ⇒ Implemented on all major platforms
  • ⇒ Large standard library, including modules for YAML, JSON, XML, CGI, OpenSSL, HTTP, FTP, RSS, curses, zlib and Tk

.

  • ⇒ Spoken as ‘Rails’, Written as ‘RoR’
  • ⇒ Open-source
  • ⇒ A Full Stack – Web application framework – MVC Framework
  • ⇒ Written In Ruby
  • ⇒ Created in 2003 by David Heinemeier Hansson (‘DHH’)
  • ⇒ Created as foundation of 37signals’ Basecamp application
  • ⇒ Released as open source in 2004
  • ⇒ Built in Database support : sqlite3 (default), MySQL, PostgreSQL
  • ⇒ With Plugins: Oracle, ibm_db, SQLServer, Frontbase
.
  • ⇒ Convention over configuration
  • ⇒ Forced to adopt an MVC style of development
.

Tools

For Ruby v1.8.x $ gem install ruby-debug-ide $ gem install ruby-debug-base . For Ruby v1.9.x $ gem install ruby-debug-ide $ gem install ruby-debug-base19x . For Ruby v2.x $ gem install ruby-debug-ide $ gem install debase .

Trying out the debugger

Step 1: Create a file sample.rb with some code

2.times do puts “hello”.upcase end

.

Step 2: Go to the Debug tab (Ctrl + Shift + D )

Step 3: Create new launch.json file

———- Add Configuration > Ruby > Listen for rdebug-ide

Step 4: Initiate a debugging session via the terminal

———- $ rdebug-ide sample.rb

Step 5: Press F5 to start debugging

———- The configuration dropdown should be set to Listen for rdebug-ide

⇒ IRB (Interactive Ruby – A Built in REPL)

Open a terminal > type irb > Press Enter > Write your code

.

⇒ PRY (Similar to IRB, but with syntax highlighting)

⇒ Apache 1 or 2

⇒ Phusion Passenger (Passenger | mod_rails | mod_rack)

⇒ Nginx (‘Engine X’)

⇒ Lighttpd (‘Lighty’)

⇒ Microsoft Internet Information Services (IIS)

⇒ WEBrick

.

Basic Ruby

Step 1: Create a test.rb file.

Step 2: Type puts “Hello, World” and save.

Step 3: Open a terminal and execute:

$ ruby test.rb

.

Your Output : Hello, WOrld

.

Simply meaning : Build strings from multiple lines

Note : There must be no space between << and the terminator.

.

Declare code to be execute before and after the program runs.

.
Sample 1 2.times do puts “hello”.upcase end . until loop . while loop . do-while loop . for loop . Upto | Downto .
If-Else . . If-Elsif . Inverse Predicate . Operators In If-Else .
Creating a Class in ruby (Conventions)

– Class Names must start with a Capital letter

– Ruby Classes are Constants, i.e When you define a class, you actually create a Class Object which is assigned to a constant. The constant becomes the class name.

. Sample 2 .
Creating a Class in ruby class ClassName def initialize(date_of_birth) days_since_birth = Date.today – Date.parse(date_of_birth) @age = days_since_birth / 365 end def can_smoke? @age >=18 end end . Sample .

Puts :

– Adds a new line at the end.

– Always returns nil.

puts “Hello World”
puts “Hello World”

Output

Hello World
Hello World

.

Print :

– Prints without a new line.

print “Hello World”
print “Hello World”

Output

Hello WorldHello World

.

p :

– Prints the objects ‘raw’ version.

– Returns the object passed to it.

p “Hello World”
p “Hello World”

Output

“Hello World”
“Hello World”

.

pp :

– Similar to p

– Pretty printing of big hashes and arrays

.

⇒ Cannot be instantiated

⇒ Cannot inherit or be derived from

⇒ Can contain classes,methods, attributes and other modules

.

Variables & Data Types

Local Variables

– Defined in a method.

– Exists only within a method or a scope.

– Begins with a lowercase letter or a _

.

Instance Variables

– Private by default.

– Available across methods for a particular instance.

– Preceded by a (@) sign followed by the variable name. @potato

.

Class Variables

– Available across different objects.

– Preceded by a (@@) sign followed by the variable name. @@user_count

.

Global Variables

– Available across different classes.

– Preceded by a ($) sign followed by the variable name. $total_amount

.

Constants

– Begins with an uppercase letter.

– Those described within a class or module can be accessed from within that class or module.

– Those described outside a class or module can be accessed globally.

.

– Getters and Setters.

. .

Numbers

– Integer number range from -230 to 230-1 or -262 to 262-1.

.

String Literals

⇒ Data structure that stores items by associated keys.

.

Hashes

Range

– A range (1..5) means it includes 1, 2, 3, 4, 5 values.

– A range (1…5) means it includes 1, 2, 3, 4 values.

Symbols

– Globally Unique.

– Unique Instances.

– Named representation of memory locations.

– Denoted with a colon. eg- :symbol_name

– Use symbols in place of string identifiers.

Enumerable Methods

⇒ .each allows you to step through each item in an array.

.

⇒ .each_with_index allows you to step through each item in an array.

⇒ provides you with the index of the item.

.

⇒ .map allows you to step through each item in an array.

.

⇒ .map will return a new modified array.

⇒ .each will return the original array

.

.

⇒ .select allows you to find an item in an array.

⇒ .reject does the opposite of select.

.

.

⇒ .reduce reduces a list down to a single value by combining things

⇒ .inject is just an alias for reduce.

⇒ Consists of two parameters – the accumulator and the current item.

⇒ Can take a starting value for the accumulator as the first argument.

.

.

CODE REUSE

1. Implementation Sharing

Provide direct access to internals

⇒ inheriting from a superclass

⇒ including a module into a class

⇒ extending an individual object using a module

⇒ patching a class or individual object directly

⇒ evaluating code in the context of a class or individual object

.

2. Behavior Sharing

By message passing between distinct objects, limiting direct access to internals.

 

⇒ decorating an object using a dynamic proxy

⇒ composing objects using simple aggregation

.

Testing

1. Installation | Source

– Add rspec-rails to the development, test namespace in the gemfile.

– rspec-rails 1.x for Rails 2.x.

group :development, :test do
gem ‘rspec-rails’, ‘~> 3.6’
end

– Install

$ bundle install

.

2. Setup an rspec directory

Creates a spec folder with rails_helper.rb and spec_helper.rb file inside.

rails generate rspec:install

.

3. Write a test

– Create a new sub-directory named requests in the spec directory

– Add a new spec file ending with _spec.rb eg: evaluate_wor_spec.rb

– Write your test. Sample test :

.

– Boilerplate specs

# RSpec hooks into built-in generators
$ rails generate model user
# RSpecs own generators
$ rails generate rspec:model user
# More Information
$ rails generate –help | grep rspec

.

4. Run the test | Tag Options

$ bundle exec rspec
# Run specs in a certain directory
$ bundle exec rspec spec/models
# Run a specific spec file
$ bundle exec rspec ./spec/requests/get_items_spec.rb
# Run a specific spec in a certain line number
$ bundle exec rspec ./spec/requests/get_items_spec.rb:23
# Run by a specific tag name
$ bundle exec rspec –tag focus
# More Information
$ bundle exec rspec –help

Basic Command Line

TitleCode
Test Ruby Installation$ ruby --version
Test Ruby Installation 2$ ruby -e "puts 1+1" #Output: 2
Generate config.yml$ devkit directory > ruby dk.rb init
Install devkit to enhance the enhanced version of ruby$ ruby dk.rb install
Create new Rails project$ rails new project-name -d mysql
Install gem file dependencies$ bundle install
Start web server$ rails server | rails s

Gem Commands

TitleCode | For More Information
Installation$ gem install gemName [gemName ...] [options] -- --build-flags [options]
Installing a gem$ gem install gemName
$ gem i gemName
Installing a specific version$ gem install rails --version 5.0.0
Installing with no documents$ gem install rails --version 5.0.0 --no-ri --no-rdoc
Uninstall a gem$ gem cleanup gemname
Show dependencies of an installed gem$ gem dependency REGEXP [options]
View doc for an installed gem$ ri RBTree
View doc for installed gems in a browser$ gem server
Generate RDoc for pre-installed gems$ gem rdoc [args] [options]
Search remote gems by name$ gem search [REGEXP] [options] $ gem search ^rails
$ gem search ^rails$ -d

Unpack an installed gem for modifications$ gem unpack rake
Query gem info in local or remote repo$ gem query [options]
Show info for the given gem$ gem info gemName[options]
Display the contents of a gem$ gem contents gemName [options]
Audit a gem’s contents without installing it$ gem fetch gemName
Build a gem$ gem build GEMSPEC_FILE [options]
Build a gem to a different output$ gem build my_gem-1.0.gemspec --output=release.gem
Check gem version$ gem -v
List locally installed gems$ gem list
Display all outdated gems$ gem outdated [options]
Update gem$ gem update --system
Open source in editor$ gem open gemName [-e COMMAND] [options]
Push gem to the gem server$ gem push gemName [options]
Get Help$ gem --help

Rails Commands

TitleCode
Install Rails$ gem install rails
Rails Help$ rails
Create new application$ rails new appName
Launch a Web Server$ rails server
$ rails server -e production -p 4000
Generate a Controller$ rails generate controller name [field[:type][:index] ...] [options]
Generate a Controller with Actions$ rails generate controller ControllerName action1 action2
$ rails generate controller Greetings hello
$ rails g controller home index
Generate a Data model$ rails generate model modelName
Destroy a Data model$ rails destroy model modelName
Interact with Rails app from command line$ rails console -e staging --sandbox
Run Ruby code in the context of Rails non-interactively$ rails runner "Model.long_running_method"
Get information about Ruby, RubyGems, Rails etc.$ rails about
Pre-compile assets in app/assets$ rails assets:precompile
Remove older compiled assets$ rails assets:clean
Clear public/assets completely$ rails assets:clobber
Search through the code for comments beginning with a keyword.

Default search directories : app, config, db, lib, and test
Default annotations : FIXME, OPTIMIZE, and TODO
Default extensions : .rb, .rake, .yml, .yaml, .ruby, .css, .js, .erb

$ rails notes
$ rails notes --annotations FIXME RELEASE
List all the defined routes$ rails routes
Clearn Rails temp directory$ rails tmp:cache:clear
$ rails tmp:sockets:clear
$ rails tmp:screenshots:clear
$ rails tmp:clear
$ rails tmp:create

Rake

  • ⇒ A standalone Ruby Utility (Task runner)
  • ⇒ Works by using the Rakefile located in the root of the project.
  • ⇒ Ruby`s implementation of Unix`s make program : rake = ruby make

.

Create a task : mytask.rake

In Project ⇒ lib ⇒ tasks ⇒ mytask.rake

desc “My Custom taks.” task :mytask do puts “I will write some code here.” end . Execute the task rake mytask

.

TitleCode
List available rake tasks$ rake -T
$ rake --tasks
Filter list$ rake -T db
Pass environment variables$ rake db:schema:dump RAILS_ENV=production
Connect to a database and export the schema of the database$ rake db:schema:dump
Migrate Database schema and data$ rake db:migrate
Undo Database migration all the way down$ rake db:migrate Version=0

Methods

Methods in ruby (Conventions)

– Methods are named lowercase (snake_case) in ruby

– Every method returns a value. (the last value in the method is returned by default).

– Methods that return true/false end with a question mark (?)

– Parameter list and parentheses can be skipped if the method doesn’t take any arguments

. .
Optional Parameters

– Methods can have multiple optional parameters (They must be either the first or the last parameters)

.
Methods returning true or false

– Methods end with a question mark (?)

.
Bang Methods

– Methods end with an exclamation mark (!)

– They usually modify the objects that they are called on

.
Attribute Reader and Writer

– attr_reader method creates an instance variable and a getter method for each attribute name passed as argument.

– attr_writer method creates an instance variable and a setter method for each attribute name passed as argument.

– attr_accessor method creates an instance variable, a getter and a setter method for each attribute name passed as argument.

– Arguments can be a Symbol or String that will be converted to Symbol

.

Operators

Arithmetic Operator

Comparison Operator

Assignment Operator

Blocks, Props & Lambdas

⇒ Enclosed in a do / end or between brackets {}.

⇒ Argument names are defined within pipe | characters.

⇒ Invoked from a function with the same name as that of the block.

⇒ Invoked using the yield statement.

⇒ Any number of arguments can be passed to a yield.

.

.

⇒ Enclosed in a do / end or between brackets {}.

⇒ In return statements: Tries to return from the current context.

.

.

⇒ A way to define a block & its parameters with some special syntax.

⇒ Just a special Proc object.

.

.

⇒ Lambdas are defined with -> {} while procs with Proc.new {}.

⇒ Procs return from the current method, while lambdas return from the lambda itself.

⇒ Procs don’t care about the correct number of arguments, while lambdas will raise an exception.

⇒ Return and break behaves differently in procs and lambdas

⇒ Next behaves same way in both procs and lambdas

.

.

⇒ Curried Function takes multiple arguments one at a time.

.

Exception Handling

Begin Rescue

.

Custom Exceptions

.