Pular para o conteúdo principal

Aula 3: Criar uma tela de autenticação de usuário em Ruby on Rails


# Criar o projeto rails ComputacaoNaPratica


No prompt:

C:\Projetos>rails new computacaonapratica
 
create create README.rdoc create Rakefile create config.ru create .gitignore create Gemfile create app create app/assets/javascripts/application.js create app/assets/stylesheets/application.css create app/controllers/application_controller.rb create app/helpers/application_helper.rb create app/views/layouts/application.html.erb create app/assets/images/.keep create app/mailers/.keep create app/models/.keep create app/controllers/concerns/.keep create app/models/concerns/.keep create bin create bin/bundle create bin/rails create bin/rake create bin/setup create config create config/routes.rb create config/application.rb create config/environment.rb create config/secrets.yml create config/environments create config/environments/development.rb create config/environments/production.rb create config/environments/test.rb create config/initializers create config/initializers/assets.rb create config/initializers/backtrace_silencers.rb create config/initializers/cookies_serializer.rb create config/initializers/filter_parameter_logging.rb create config/initializers/inflections.rb create config/initializers/mime_types.rb create config/initializers/session_store.rb create config/initializers/to_time_preserves_timezone.rb create config/initializers/wrap_parameters.rb create config/locales create config/locales/en.yml create config/boot.rb create config/database.yml create db create db/seeds.rb create lib create lib/tasks create lib/tasks/.keep create lib/assets create lib/assets/.keep create log create log/.keep create public create public/404.html create public/422.html create public/500.html create public/favicon.ico create public/robots.txt create test/fixtures create test/fixtures/.keep create test/controllers create test/controllers/.keep create test/mailers create test/mailers/.keep create test/models create test/models/.keep create test/helpers create test/helpers/.keep create test/integration create test/integration/.keep create test/test_helper.rb create tmp/cache create tmp/cache/assets create vendor/assets/javascripts create vendor/assets/javascripts/.keep create vendor/assets/stylesheets create vendor/assets/stylesheets/.keep run bundle install Fetching gem metadata from https://rubygems.org/............. Fetching version metadata from https://rubygems.org/... Fetching dependency metadata from https://rubygems.org/.. Resolving dependencies... Fetching rake 12.1.0 Installing rake 12.1.0 Using i18n 0.8.6 Using minitest 5.10.3 Using thread_safe 0.3.6 Using builder 3.2.3 Using erubis 2.7.0 Using mini_portile2 2.2.0 Using rack 1.6.8 Using mime-types-data 3.2016.0521 Using arel 6.0.4 Using debug_inspector 0.0.3 Using bundler 1.15.4 Fetching byebug 9.1.0 Installing byebug 9.1.0 with native extensions Using coffee-script-source 1.12.2 Using execjs 2.7.0 Fetching thor 0.20.0 Installing thor 0.20.0 Using concurrent-ruby 1.0.5 Using ffi 1.9.18 (x64-mingw32) Fetching multi_json 1.12.2 Installing multi_json 1.12.2 Using json 1.8.6 Using rb-fsevent 0.10.2 Using rdoc 4.3.0 Using tilt 2.0.8 Using sqlite3 1.3.13 (x64-mingw32) Using turbolinks-source 5.0.3 Using tzinfo 1.2.3 Using nokogiri 1.8.0 (x64-mingw32) Using rack-test 0.6.3 Using mime-types 3.1 Using binding_of_caller 0.7.2 Using coffee-script 2.4.1 Using uglifier 3.2.0 Using sprockets 3.7.1 Using rb-inotify 0.9.10 Using sdoc 0.4.2 Using turbolinks 5.0.1 Using activesupport 4.2.8 Using tzinfo-data 1.2017.2 Using loofah 2.0.3 Using mail 2.6.6 Using sass-listen 4.0.0 Using rails-deprecated_sanitizer 1.0.3 Using globalid 0.4.0 Using activemodel 4.2.8 Using jbuilder 2.7.0 Using rails-html-sanitizer 1.0.3 Using sass 3.5.1 Using rails-dom-testing 1.0.8 Using activejob 4.2.8 Using activerecord 4.2.8 Using actionview 4.2.8 Using actionpack 4.2.8 Using actionmailer 4.2.8 Using railties 4.2.8 Fetching sprockets-rails 3.2.1 Installing sprockets-rails 3.2.1 Using coffee-rails 4.1.1 Using jquery-rails 4.3.1 Using rails 4.2.8 Using sass-rails 5.0.6 Using web-console 2.3.0 Bundle complete! 12 Gemfile dependencies, 60 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed.
C:\Projetos>cd computacaonapratica C:\Projetos\computacaonapratica>

#Iniciar o servidor



C:\Projetos\computacaonapratica>rails s
 
=> Booting WEBrick => Rails 4.2.8 application starting in development on http://localhost:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server [2017-09-13 05:16:16] INFO WEBrick 1.3.1 [2017-09-13 05:16:16] INFO ruby 2.2.6 (2016-11-15) [x64-mingw32] [2017-09-13 05:16:16] INFO WEBrick::HTTPServer#start: pid=18536 port=3000
Abrir o navegador em http://localhost:3000/

#Parar o servidor


Ctrl + c 
Started GET "/" for ::1 at 2017-09-13 05:17:29 -0300 Processing by Rails::WelcomeController#index as HTML Rendered C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.8/lib/rails/templates/rails/welcome/index.html.erb (25.7ms) Completed 200 OK in 272ms (Views: 250.5ms | ActiveRecord: 0.0ms) [2017-09-13 05:19:46] INFO going to shutdown ... [2017-09-13 05:19:46] INFO WEBrick::HTTPServer#start done. Exiting Deseja finalizar o arquivo em lotes (S/N)? S C:\Projetos\computacaonapratica>

#Instalar o bootstrap


Instalar e Abrir o Sublime Text3
 
Abrir o arquivo C:\Projetos\computacaonapratica\Gemfile e adicionar
 
gem 'bootstrap-sass', '~> 3.3.6'

Salvar o arquivo Gemfile

No prompt executar: C:\Projetos\computacaonapratica>bundle install

C:\Projetos\computacaonapratica>bundle install Fetching gem metadata from https://rubygems.org/........... Fetching gem metadata from https://rubygems.org/.............. Fetching gem metadata from https://rubygems.org/... Resolving dependencies... Using rake 12.1.0 Using i18n 0.8.6 Using minitest 5.10.3 Using thread_safe 0.3.6 Using tzinfo 1.2.3 Using activesupport 4.2.8 Using builder 3.2.3 Using erubis 2.7.0 Using mini_portile2 2.2.0 Using nokogiri 1.8.0 (x64-mingw32) Using rails-deprecated_sanitizer 1.0.3 Using rails-dom-testing 1.0.8 Using loofah 2.0.3 Using rails-html-sanitizer 1.0.3 Using actionview 4.2.8 Using rack 1.6.8 Using rack-test 0.6.3 Using actionpack 4.2.8 Using globalid 0.4.0 Using activejob 4.2.8 Using mime-types-data 3.2016.0521 Using mime-types 3.1 Using mail 2.6.6 Using actionmailer 4.2.8 Using activemodel 4.2.8 Using arel 6.0.4 Using activerecord 4.2.8 Using execjs 2.7.0 Fetching autoprefixer-rails 7.1.4 Installing autoprefixer-rails 7.1.4 Using debug_inspector 0.0.3 Using binding_of_caller 0.7.2 Using rb-fsevent 0.10.2 Using ffi 1.9.18 (x64-mingw32) Using rb-inotify 0.9.10 Using sass-listen 4.0.0 Using sass 3.5.1 Using bootstrap-sass 3.3.7 Using bundler 1.16.0.pre.2 Using byebug 9.1.0 Using coffee-script-source 1.12.2 Using coffee-script 2.4.1 Using thor 0.20.0 Using railties 4.2.8 Using coffee-rails 4.1.1 Using concurrent-ruby 1.0.5 Using multi_json 1.12.2 Using jbuilder 2.7.0 Using jquery-rails 4.3.1 Using json 1.8.6 Using sprockets 3.7.1 Using sprockets-rails 3.2.1 Using rails 4.2.8 Using rdoc 4.3.0 Using tilt 2.0.8 Using sass-rails 5.0.6 Using sdoc 0.4.2 Using sqlite3 1.3.13 (x64-mingw32) Using turbolinks-source 5.0.3 Using turbolinks 5.0.1 Using tzinfo-data 1.2017.2 Using uglifier 3.2.0 Using web-console 2.3.0 Bundle complete! 13 Gemfile dependencies, 62 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed. C:\Projetos\computacaonapratica>
Verificar que o bootstrap-sass foi instalado

# Configurar o bootstrap


Renomear o arquivo app/assets/stylesheets/application.css para:
app/assets/stylesheets/application.scss

Limpar todo o conteúdo do arquivo application.scss 

No arquivo application.scss adicionar:

@import "bootstrap-sprockets";
@import "bootstrap";

Abrir o arquivo app/assets/javascripts/application.js
# Adicionar o bootstrap ABAIXO de //= require jquery

//= require jquery
//= require bootstrap-sprockets

#Iniciar o servidor

C:\Projetos\computacaonapratica>rails s
 
=> Booting WEBrick => Rails 4.2.8 application starting in development on http://localhost:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server [2017-09-13 05:16:16] INFO WEBrick 1.3.1 [2017-09-13 05:16:16] INFO ruby 2.2.6 (2016-11-15) [x64-mingw32] [2017-09-13 05:16:16] INFO WEBrick::HTTPServer#start: pid=18536 port=3000
Abrir o navegador em http://localhost:3000/

#Parar o servidor


Ctrl + c 
 
Started GET "/" for ::1 at 2017-09-13 05:17:29 -0300 Processing by Rails::WelcomeController#index as HTML Rendered C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.8/lib/rails/templates/rails/welcome/index.html.erb (25.7ms) Completed 200 OK in 272ms (Views: 250.5ms | ActiveRecord: 0.0ms) [2017-09-13 05:19:46] INFO going to shutdown ... [2017-09-13 05:19:46] INFO WEBrick::HTTPServer#start done. Exiting Deseja finalizar o arquivo em lotes (S/N)? S C:\Projetos\computacaonapratica>

# Criar a página de login para usuário


## Instalando o Devise

No arquivo Gemfile adicionar

gem 'devise', '~> 4.2'
 
Salvar o arquivo Gemfile
 
 
Executar o comando:
C:\Projetos\computacaonapratica>bundle install
 
Em seguida, executar o comando: 
 
C:\Projetos\computacaonapratica>rails g devise:install
 
create config/initializers/devise.rb create config/locales/devise.en.yml =============================================================================== Some setup you must do manually if you haven't yet: 1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb: config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } In production, :host should be set to the actual host of your application. 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root to: "home#index" 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example: <'p class="notice"><'%= notice %><'/p> <'p class="alert"><'%= alert %><'/p> 4. You can copy Devise views (for customization) to your app by running: rails g devise:views ===============================================================================

# Configurar o Devise


## Adicionar no arquivo config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
 
Salvar arquivo 
## Adicionar no arquivo config/routes.rb:
root 'pages#home'

Salvar arquivo
## Criar a rota
Executar o comando: 

C:\Projetos\computacaonapratica>rake routes
 
Prefix Verb URI Pattern Controller#Action new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy user_password POST /users/password(.:format) devise/passwords#create new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel user_registration POST /users(.:format) devise/registrations#create new_user_registration GET /users/sign_up(.:format) devise/registrations#new edit_user_registration GET /users/edit(.:format) devise/registrations#edit PATCH /users(.:format) devise/registrations#update PUT /users(.:format) devise/registrations#update DELETE /users(.:format) devise/registrations#destroy root GET / pages#home
## Criar a pasta app/views/pages

## Criar o arquivo home.html.erb dentro da pasta app/views/pages

Com o seguinte conteúdo:
<p>pages#home</p>
<%= link_to "Log in", new_user_session_path %> | <%= link_to "Log out", destroy_user_session_path, method: :delete %>
 
Salvar o arquivo 
## Criar o controlador PagesController em app/controller/pages_controller.rb

Com o seguinte conteúdo:

class PagesController < ApplicationController
  def home
      
  end

end
 
Salvar o arquivo 
## No arquivo app/views/layouts/application.html.erb:
<html> 
...
   <body>
       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>
       <%= yield %>
   </body>
</html>
 
Salvar o arquivo 

# Criar o model User


C:\Projetos\computacaonapratica>rails g devise User
 
invoke active_record create db/migrate/20170809005335_devise_create_users.rb create app/models/user.rb invoke test_unit create test/models/user_test.rb create test/fixtures/users.yml insert app/models/user.rb route devise_for :users

# Adicionar no Banco de Dados


rails 4> C:\Projetos\computacaonapratica>rake db:migrate
== 20170809005335 DeviseCreateUsers: migrating ================================ -- create_table(:users) -> 0.0033s -- add_index(:users, :email, {:unique=>true}) -> 0.0019s -- add_index(:users, :reset_password_token, {:unique=>true}) -> 0.0013s == 20170809005335 DeviseCreateUsers: migrated (0.0092s) =======================

# Abrir o programa DB Browser for SQLite que está instalado na máquina


Selecionar o esquema em "Abrir banco de dados" com o arquivo:
C:\Projetos\computacaonapratica/db/development.sqlite3

Abrir a tabela "Users" em Navergar dados > Tabela "User"

# Adicionar as Views

C:\Projetos\computacaonapratica>rails g devise:views
 
Expected boolean default value for '--markerb'; got :erb (string) invoke Devise::Generators::SharedViewsGenerator create app/views/devise/shared create app/views/devise/shared/_links.html.erb invoke form_for create app/views/devise/confirmations create app/views/devise/confirmations/new.html.erb create app/views/devise/passwords create app/views/devise/passwords/edit.html.erb create app/views/devise/passwords/new.html.erb create app/views/devise/registrations create app/views/devise/registrations/edit.html.erb create app/views/devise/registrations/new.html.erb create app/views/devise/sessions create app/views/devise/sessions/new.html.erb create app/views/devise/unlocks create app/views/devise/unlocks/new.html.erb invoke erb create app/views/devise/mailer create app/views/devise/mailer/confirmation_instructions.html.erb create app/views/devise/mailer/email_changed.html.erb create app/views/devise/mailer/password_change.html.erb create app/views/devise/mailer/reset_password_instructions.html.erb create app/views/devise/mailer/unlock_instructions.html.erb

# Iniciar o servidor e cadastrar um novo usuário


C:\Projetos\computacaonapratica>rails s

Acessar a página http://localhost:3000/users/sign_up

Cadastrar um novo usuário

# O sistema direciona para a página Home.

Verificar no banco de dados se o usuário foi criado com sucesso.

# Fazer o log out.

# Fazer o login

# Mensagem de login com sucesso


Comentários

Postagens mais visitadas deste blog

Onde implementar um novo método ou variável?

Como sabemos, o framework  Ruby on Rails é baseado na arquitetura MVC. Desta forma, as principais pastas do projeto abaixo do nível /app são:
assets: onde ficam os CSS, JavaScripts e Imagens da aplicação.models: onde ficam os objetos da aplicação, geralmente representam uma tabela do Banco de Dados ou um Relacionamento entre tabelas. O nome dos arquivos geralmente estão no padrão "<nome_da_tabela>.rb" controllers: onde ficam as classes de controle, que permitem que os objetos (model) acessem a camada de apresentação (view). 
O nome dos arquivos geralmente estão no padrão "<nome_da_tabela>s_controller.rb"Observe que o nome da tabela deve ser no plural.views: onde ficam as páginas html da aplicação.O nome dos arquivos geralmente estão no padrão "<metodo_do_controlador>".html.erb Desta forma, o programador tem que saber onde irá criar novos métodos na aplicação, de forma que eles fiquem visíveis na camada de apresentação (View).


Quando for n…

Brincar para Aprender!

Aprendendo a usar CSS, este joguinho é bem simples e prático. Com ele dá para aprender a usar os comandos CSS-Flex para sua aplicação. Tente colocar os sapinhos em cada posição corretamente. Acesse o site: https://codepip.com/

View - Dicas para Programadores Ruby on Rails

View - Camada de Apresentação (/*.html.erb)Como exibir uma data no formato dd/mm/aa?
Se o sistema está exibindo a data em formato mm/dd/aaaa, por exemplo:

No arquivo <suapagina>.html.erb basta adicionar o seguinte comando:

Antes:
Data Inicial: <%= @data_inicial.value.to_date %>
Data Inicial: 01/28/2017


Depois:
Data Inicial: <%= l @data_inicial.value.to_date, format:  "%d/%m/%Y" %>
Data Inicial: 28/01/2017

Como transformar um número fracionário (float, double, decimal) em inteiro? Se o sistema está exibindo um número com uma ou duas casas decimais, por exemplo:

No arquivo <suapagina>.html.erb basta adicionar o seguinte comando:

Antes 

Idade: <%= @idade %> anos
Idade: 25.0 anos

Depois

Idade: <%= @idade.to_i %> anos
Idade: 25 anos

Como formatar um conteúdo para adicionar quebras de linha no texto? Se o sistema está exibindo um texto sem quebra de linhas, mas o usuário digitou com quebra de linha, por exemplo:


No arquivo <suapagina>.html.e…