Tue 20 Mar 2018

Ruby on Rails

It's a server-side website framework, like Django. It aims to have do everything you need, and to have sensible built-in starting decisions.

It has:

  • routing
  • templating
  • a database ORM (object relational mapper) using the active record pattern
  • internationalization
  • basic authentication and authorisation
  • caching
  • user sessions
  • backend job scheduling
  • JavaScript, CSS and image pipeline (pre-processing, minification and so on)

Routing passes a URL to a Controller. The Controller may modify and query the database as needed. It then uses a View to render the data.

Routing

Routing has a nice little DSL.

It includes an idea of resources, which map REST to CRUD.

Controllers

They have three methods for returning responses:

render
return a normal response
redirectto
return an HTTP status code
head
return some HTTP headers

If you inherit from ActionController, it will find and render the appropriate view by default.

You can override methods corresponding to the CRUD operations if you want different behaviour.

Views

You usually write views as .html.erb files, which are a templating language. This has keywords for loops, if statements, forms and so on.

Alternatively, there's a programmatic XML creating thing called Builder, and a third party Gem called JBuilder for making JSON.

You can also break your templates up so that you can share parts between them.

Model

Uses an ORM to generate a database schema. It appears to be sensible, covering most of SQL, allowing joins and prefetching. You can handwrite SQL when you need to.

Uses the Active Record pattern, which magically injects database code into the domain model.

There are some event hooks relating to database operations, which you can add your own code to.

Models can also include validation code.

Client Side

Rails defaults to using CoffeeScript and SCSS.

Rails Command Line Interface

There is a rails command:

rails new name
set up a new project
rails server
run development web server
rails console
read-eval-print-loop
rails dbconsole
interactive database session
rails generate model Name field:type field:type
create a model class