Ruby on Rails

Partie 2 : Les bases d'une application Rails

 

https://slides.com/sophiedeziel/ruby-and-rails-milestone-2

Dossier app

├── app
│   ├── assets
│   │   ├── images
│   │   ├── javascripts
│   │   │   └── application.js
│   │   └── stylesheets
│   │       └── application.css
│   ├── controllers
│   │   ├── application_controller.rb
│   │   └── concerns
│   ├── helpers
│   │   └── application_helper.rb
│   ├── mailers
│   ├── models
│   │   └── concerns
│   └── views
│       └── layouts
│           └── application.html.erb

Dossier app

Source: https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/le-fonctionnement-de-django

Base du blog

rails generate scaffold post title content:text
→ rails generate scaffold post title content:text
Running via Spring preloader in process 53358
      invoke  active_record
      create    db/migrate/20160421004111_create_posts.rb
      create    app/models/post.rb
      invoke    test_unit
      create      test/models/post_test.rb
      create      test/fixtures/posts.yml
      invoke  resource_route
       route    resources :posts
      invoke  scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb
      invoke    test_unit
      create      test/controllers/posts_controller_test.rb
      invoke    helper
      create      app/helpers/posts_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/posts/index.json.jbuilder
      create      app/views/posts/show.json.jbuilder
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/posts.coffee
      invoke    scss
      create      app/assets/stylesheets/posts.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.scss

ActiveRecord

      invoke  active_record
      create    db/migrate/20160421004111_create_posts.rb
      create    app/models/post.rb

Lien avec la base de données

Le 'generate' a créé:

Migrations

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content

      t.timestamps null: false
    end
  end
end

db/migrate/20160421004111_create_posts.rb

Migrations

→ rake db:migrate
== 20160421004111 CreatePosts: migrating ======================================
-- create_table(:posts)
   -> 0.0013s
== 20160421004111 CreatePosts: migrated (0.0013s) =============================

Model

class Post < ActiveRecord::Base
end

app/models/post.rb

Routes

      invoke  resource_route
       route    resources :posts

Le 'generate' a créé:

Rails.application.routes.draw do
  resources :posts
end
→ rake routes
   Prefix Verb   URI Pattern               Controller#Action
    posts GET    /posts(.:format)          posts#index
          POST   /posts(.:format)          posts#create
 new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
     post GET    /posts/:id(.:format)      posts#show
          PATCH  /posts/:id(.:format)      posts#update
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy

config/routes.rb

Routes

Rails.application.routes.draw do
  root 'posts#index'
  resources :posts
end
→ rake routes
   Prefix Verb   URI Pattern               Controller#Action
     root GET    /                         posts#index
    posts GET    /posts(.:format)          posts#index
          POST   /posts(.:format)          posts#create
 new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
     post GET    /posts/:id(.:format)      posts#show
          PATCH  /posts/:id(.:format)      posts#update
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy

config/routes.rb

Notre blog

Est laid...

(Il faut juste lui donner un peu d'amour)

ActionView et ActionController

scaffold_controller
      create    app/controllers/posts_controller.rb
      invoke    erb
      create      app/views/posts
      create      app/views/posts/index.html.erb
      create      app/views/posts/edit.html.erb
      create      app/views/posts/show.html.erb
      create      app/views/posts/new.html.erb
      create      app/views/posts/_form.html.erb

Layout, template et partials

app/views
├── layouts
│   └── application.html.erb
└── posts
    ├── _form.html.erb
    ├── edit.html.erb
    ├── index.html.erb
    ├── index.json.jbuilder
    ├── new.html.erb
    ├── show.html.erb
    └── show.json.jbuilder
<!DOCTYPE html>
<html>
<head>
  <title>DemoAtelier</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

Layout

app/views/layouts/application.html.erb

<h1>Editing Post</h1>

<%= render 'form' %>

<%= link_to 'Show', @post %> |
<%= link_to 'Back', posts_path %>

Template

app/views/posts/edit.html.erb

<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Partial

app/views/posts/_form.html.erb

Créer un post

Dolor quinoa placeat exercitation labore. Kale chips wayfarers wolf dolor, paleo affogato fugiat dolore. Delectus gastropub pop-up quis, placeat eiusmod messenger bag yuccie deserunt banjo. Keytar art party bicycle rights, sunt sapiente do blog literally single-origin coffee plaid adipisicing aute flannel. Butcher skateboard fashion axe salvia, sed kogi excepteur hammock ut. Taxidermy blog est, tumblr godard truffaut id. Post-ironic health goth whatever fixie magna, fap gochujang gluten-free nihil austin tacos literally marfa yr migas.

Placeat thundercats small batch messenger bag vinyl tofu. Wolf brunch fap, bespoke nisi venmo kale chips skateboard tacos pop-up synth mlkshk tofu church-key. Est mustache franzen roof party tofu semiotics tacos mumblecore, eiusmod tattooed +1. 8-bit chillwave blue bottle leggings bespoke. Dreamcatcher vinyl church-key, health goth kinfolk consectetur adipisicing scenester meditation. Consectetur gluten-free YOLO, authentic chartreuse slow-carb trust fund accusamus synth enim iPhone mixtape keffiyeh +1 post-ironic. Tote bag sint reprehenderit, aliqua VHS ennui incididunt non XOXO messenger bag velit chartreuse fap.

Four dollar toast photo booth synth, cray hella chillwave man bun deserunt crucifix asymmetrical fingerstache 90's cillum food truck poutine. Fingerstache listicle vero, migas skateboard wayfarers church-key four loko small batch echo park. Etsy knausgaard seitan small batch enim, tacos biodiesel cronut. Vice quinoa gochujang incididunt PBR&B, yuccie distillery pabst godard messenger bag. Affogato next level paleo, duis chartreuse leggings bushwick portland ea yuccie disrupt anim. Aesthetic narwhal occupy, cred eu beard excepteur wayfarers thundercats deserunt pour-over. Truffaut vegan whatever, elit 3 wolf moon esse godard lumbersexual occupy man bun pop-up brunch hammock.

Authentic kale chips gluten-free meggings thundercats veniam. Delectus neutra ex waistcoat, mustache nostrud try-hard poutine mlkshk gentrify aesthetic reprehenderit heirloom. Bespoke pug occaecat thundercats artisan. Voluptate nostrud culpa synth quis, normcore vero before they sold out farm-to-table. Yuccie beard small batch photo booth, cray retro austin 8-bit cillum etsy pour-over fanny pack enim tempor. Delectus humblebrag shoreditch locavore, chia tilde labore lumbersexual man bun tousled williamsburg art party. Gentrify beard in bespoke helvetica, kogi swag twee proident.

On a tout ce qu'il faut

Mais pour la gestion...

Home Controller

→ rails generate controller home index
Running via Spring preloader in process 54158
      create  app/controllers/home_controller.rb
       route  get 'home/index'
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
      invoke  test_unit
      create    test/controllers/home_controller_test.rb
      invoke  helper
      create    app/helpers/home_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/home.coffee
      invoke    scss
      create      app/assets/stylesheets/home.scss

Home Controller

Rails.application.routes.draw do
  root 'home#index'

  get 'home/index'

  resources :posts
end

config/routes.rb

Home Controller

class HomeController < ApplicationController
  def index
    @posts = Post.all
  end
end

app/controllers/home_controller.rb

Home View

<% @posts.each do |post| %>
  <article>
    <h2><%= post.title %></h2>
    <div class='post-meta'>
      Last updated: <%= post.created_at %>
    </div>

    <div class='post-content'>
      <%= post.content %>
    </div>
  </article>
<% end %>

app/views/home/index.html.erb

Home View

<% @posts.each do |post| %>
  <article>
    <h2><%= post.title %></h2>
    <div class='post-meta'>
      Last updated: <%= post.created_at.to_s(:long) # formater la date pour un humain %>
    </div>

    <div class='post-content'>
      <%= raw post.content  # raw permet de rendre quelques éléments html %>
    </div>
  </article>
<% end %>

app/views/home/index.html.erb

Asset Pipeline

app/assets
├── images
├── javascripts
│   ├── application.js
│   ├── blogs.coffee
│   ├── home.coffee
│   └── posts.coffee
└── stylesheets
    ├── application.css
    ├── blogs.scss
    ├── home.scss
    ├── posts.scss
    └── scaffolds.scss

Asset Pipeline

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
/*
 *= require_tree .
 *= require_self
 */

application.js

application.css

<!DOCTYPE html>
<html>
<head>
  <title>DemoAtelier</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body class="<%= controller_name %>_controller">

<%= yield %>

</body>
</html>

layouts/application.html.erb

.home_controller {
  width: 100%;
  font-family: 'Helvetica';

  article {
    width: 600px;
    margin: 10px auto 0px auto;
    border-bottom: 1px solid #333333;
  }

  h2 {
    font-size: 4em;
    font-family: "Palatino Linotype", "Book Antiqua", Palatino, serif ;
  }

  .post-meta {
    color: #999999;
  }
}

app/assets/stylesheets/home.css.scss

Fin de la partie 2

Bon appétit!

Ruby on Rails milestone 2

By Sophie Déziel

Ruby on Rails milestone 2

  • 1,539