Gustavo Diel
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Instalando Bootstrap e criando uma Home ###### tags: `tutorial` `rails` `bootstrap` --- [ToC] ## :books: MVC Antes de iniciar as alterações no Rails, temos que entender o que precisamos fazer o como as coisas funcionam. Internamente, o Rails utiliza o MVC para a organização das classes, modelos e arquivos. O MVC é um *design pattern* ou padrão de design, que significa ==Model-View-Controller==, que lida com três principais entidades: - **Model:** O modelo é a entidade que **guarda as informações** que queremos, e possui algumas poucas e simples regras de negócio pertinentes apenas ao modelo. - **View:** É responsável por apresentar as informações pro usuário. - **Controller:** É a entidade que **combina o modelo com a *view***. Faz as buscas nos bancos de dados, processa as informações, aplica regras de negócio e envia para o *front*. :::info :bulb: **Nota:** Isso é só um breve resumo do modelo. Sugiro pesquisar melhor quais são os ideias do MVC. ::: ## :memo: Instalando o Bootstrap O [Bootstrap](https://getbootstrap.com/) é uma ferramenta que facilita o desenvolvimento de sites responsivos, tendo uma abordagem *mobile first*. Ele pode ser instalado como uma gema ou como uma biblioteca do JS. Como as novas versões do Rails utilizam o `webpacker` e ja precisam do `yarn` por padrão, nõs iremos aproveitar isso e instalar como uma biblioteca JS. Antes de mais nada, digite no terminal: ```shell yarn add bootstrap jquery ``` O Yarn é um utilitário que auxilia na instalação de bibliotecas JS. `add` quer dizer que vamos adicionar a(s) biblioteca(s) e `bootstrap` e `jquery` são as bibliotecas que precisamos. Agora temos que ativá-las. Para isso, abra o arquivo `config/webpack/environment.js` e antes da linha ` module.exports = environment` adicione o seguinte: ```javascript=3 const webpack = require("webpack") environment.plugins.append("Provide", new webpack.ProvidePlugin({ $: 'jquery/src/jquery', jQuery: 'jquery/src/jquery' })) ``` Então entre em `app/javascript/packs/application.js` e adicione depois do ultimo `require`: ```javascript=10 require("jquery") require("bootstrap") ``` E por fim, entre em `app/assets/stylesheets/application.css` e antes da linha ` *= require_tree .` adicione a seguinte linha: ```css=13 *= require bootstrap ``` Também podemos importar os ícone que o Bootstrap fornece e imports do JQueryUI (que dão alguns recursos a mais para mexer com o front). Para isso, basta entrar em `app/views/layouts/application.html.erb` e **depois** de `javascript_pack_tag` podemos adicionar isso: ```htmlembedded=8 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" ></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> ``` :::success :tada: **Sucesso:** Agora que temos o Bootstrap instalado, vamos criar nossa homepage. ::: ## Criando a Home Page Vamos criar o nosso controlador da Home. Felizmente o Rails já trás várias utilidades para facilitar nossa vida, e uma delas é o `rails generate`. Ele serve para gerar arquivos a partir de um *template*. No nosso caso, queremos gerar um controlador. Esse controlador vai ser o nosso controlador da Home, e só vai ter um método inicialmente, o `index`. Então vamos criá-lo: ```shell rails generate controller Home index ``` Essa linha usa o utilitário `rails generate` para criar um `controller` chamado `Home` com o(s) método(s) `index`. :::warning **Nota:** Caso aconteca um erro contendo **`Please run yarn install --check-files to update`**, basta executar isso: ```shell sudo chown ${USER}:${USER} -R . yarn install ``` e então é so re-executar ::: Esse comando vai gerar (entre outros arquivos) o nosso controller em `app/controller/home.rb` e a view `app/view/home/index.html.erb`. Para que a gente possa chegar na view, é necessário configurar as rotas. Então vamos entrar em `config/routes.rb` e substituir `get 'home/index'` por: ```ruby=2 root 'home#index', as: :home ``` Essa linha especifica a `root` ou a página raiz da página. Ela é a primeira página que aparece quando acessamos a URL do nosso site. O segundo argumento tem um formato especial. Nele temos o controlador e o método a ser executado, dividido pelo caractére #. Nesse exemplo, indicamos o controlador `Home` e o método `index`. O `as: :home` no final indica um nome que damos à rota para usarmos os métodos de rota do Rails. Podemos subir nosso app agora, e se entrarmos em [http://localhost:3000](http://localhost:3000/) veremos algo semelhante a isso: <img src="https://i.imgur.com/qCLSzMu.png" align="center" /> :::info :memo: **Lembrete:** Para levantar o app, basta digitar no terminal **`docker compose up --build`**. ::: Conseguimos alguma coisa, mas poderia ser um pouco melhor :smile: Então vamos começar alterando a nossa *view* para isso: ```htmlembedded=1 <div class="card mx-auto" style="width: 40%; min-width: 200px; margin-top: 10%"> <div class="card-header"> <i class="bi-box-arrow-in-right"></i> Login </div> <div class="card-body"> <h5 class="card-title">Bem Vindo!</h5> <p class="card-text">Seja bem vindo ao meu site :D</p> <p class="card-text">Por favor, faça login ou se cadastre:</p> <div class="btn-group d-flex" role="group"> <%= link_to 'Entrar', '', class: 'btn btn-primary', method: 'get' %> <%= link_to 'Criar conta', '', class: 'btn btn-secondary', method: 'get' %> </div> </div> </div> ``` Se tudo der certo, você deve se deparar com isso: ![](https://i.imgur.com/JJKZ5gB.png) :::info :bulb: **Nota:** Vale a pena ver a **[documentação do Bootstrap](https://getbootstrap.com/docs/5.0/components/)** para entender o que estamos fazendo assim como quais componentes ele nos fornece! ::: Mas ainda falta coisas na página e esses botões não fazem nada ainda. Sobre a página, podemos colocar uma [**NavBar**](https://getbootstrap.com/docs/5.0/components/navbar/)! ### Navbar A Navbar é um componente que fica no topo da página e fornece algumas ferramentas. Idealmente, ela é um objeto que aparece em todas as páginas e nos **ajuda a navegar pelo site**, com links para as áreas mais importantes. Como o objetivo é mostrar a Navbar em todas as páginas, queremos ao máximo não precisar duplicar o código dela. Por isso, iremos altera o arquivo `app/views/layouts/application.html.erb`. O funcionamento desse arquivo é um pouco diferente dos outros arquivos de *view*. Toda vez que o Rails vai apresentar uma página, ele é carregado. No meio do código, tem uma linha que é: `<%= yield %>`. Essa `yield` espera que os arquivos específicos de cada rota sejam carregados e retornem algum resultado, e então, o `yield` é substituído pelo retorno. Por isso, se precisamos fazer um código que apareça em todas as telas do nosso app, esse `application.html.erb` é um bom começo. E é o que vamos fazer. Antes de editar o `application.html.erb`, vamos criar um template da navbar, para que o código dela esteja separado e futuramente seja fácil de editá-lo. Vamos criar o arquivo `app/views/layouts/_navbar.html.erb` (note o `_`, ele é importante!). Dentro desse arquivo, insira: ```htmlembedded= <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <%= link_to 'PastaDoProjeto', home_path, class: 'navbar-brand' %> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <%= link_to 'Home', home_path, class: 'nav-link active' %> </li> </ul> </div> </nav> ``` :::warning :memo: **Lembrete:** Não se esqueça de mudar o código para conter o nome do seu App, assim como adicionar mais coisas que deseja. ::: :::info :bulb: **Nota:** Perceba que na linha 11 usamos o **`home_path`** no **`link_to`**, que foi criado com aquele **`as: :home`** que adicionamos antes. ::: E agora no `application.html.erb` iremos colocar o seguinte código antes da linha do `yield`: ```htmlembedded=15 <%= render 'layouts/navbar' %> ``` E quando recarregarmos a página, veremos isso: ![](https://i.imgur.com/QYYy7Dg.png) :::success :rocket: **Próximo passo:** Siga o link ➜ [Fazendo Login com Devise](https://hackmd.io/RcwgP49yQlOV7sOdAaX2UQ) :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully