Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save jendiamond/f6432d1a102b2ca6a429 to your computer and use it in GitHub Desktop.

Select an option

Save jendiamond/f6432d1a102b2ca6a429 to your computer and use it in GitHub Desktop.
L.A. Rails Learners First App

LA Rails Learners - The Parallell Project

Homework for each week can be found in issues.

Vanilla Rails

We are starting out this project by creating a vanilla Rails App. Once built you will have the base from which you can build any number of other applications.

Our Vanilla Rails Base App will include

  • An new instance of a Rails App
  • Postgres Database
  • A User Model with fields first_name, last_name, email
  • Devise
  • Bootstrap
  • Rspec
  • README.md with clear directions to the installation and application of all the above.

Phase One - New Rails App with Postgres and a User Model - Issue #6

To install vagrant see https://github.com/webapp-builders/groundwork

Create a new rails app with a Postgres database (change your_app_name to something like jane_doe_firstapp)

$ rails new your_app_name --database=postgresql

Changes directories into your new Rails app

$ cd your_app_name

Create the database, load the schema and initialize it with the seed data

$ rake db:setup
     -- enable_extension("plpgsql")  
     -> 0.0822s  
     -- initialize_schema_migrations_table()  
     -> 0.0550s  
     -- enable_extension("plpgsql")  
     -> 0.1057s  
     -- initialize_schema_migrations_table()  
     -> 0.0290s

All Rails db Rake Tasks and What They Do

Active Record Migrations
Migrations are a feature of Active Record that allows you to evolve your database schema over time. Rather than write schema modifications in pure SQL, migrations allow you to use an easy Ruby DSL to describe changes to your tables.

Run the Migration (Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.)

$ rake db:migrate

Create a model with the fields first_name, last_name, email

$ rails g scaffold User first_name:string last_name:string email:string

Run the migration again

$ rake db:migrate

Create a local git repository

$ git init

Add your remote repositories

$ git remote add origin [email protected]:your_github/your_app.git
$ git remote add rails_learner [email protected]:LARailsLearners/your_app.git

Check out that your remotes were added

$ git remote -v
Push your app to your GitHub repository AND to this repository (github.com/LARailsLearners)

To push to your own repository you run this command: you run this command:

`$ git push origin master`

To push to the LARailsLearners repository you run this command:

`$ git push rails_learner master`

If you previously created an ssh key, you'll need to approve it at:
https://github.com/settings/ssh/audit/854149/policy

Some useful reading:

Rakefile


Phase 2 - Authentication / Devise - Issue #2

"Authentication is the process of establishing, and subsequently confirming, a site user’s identity. It is how an app recognises, who you are." ~ http://www.gotealeaf.com/blog/authentication-methods-in-rails

Most of us will use the very popular solution called Devise which is a Rails Gem. But use whatever method you want to use.

"Most Ruby on Rails applications require user registration and authentication mechanisms. Developing these from scratch requires a lot of time and effort – thankfully, there's Devise. Using the Devise gem, you can set up a full-fledged user authentication system within minutes." ~ https://www.digitalocean.com/community/tutorials/how-to-configure-devise-and-omniauth-for-your-rails-application

Install Devise

Some resources:

=====

These are very basic directions. The notice and alert messages can be made better with Bootstrap. The directions for installing Devise in the Rails Girls Guides by Piotr Steininger show you how to make it better. http://guides.railsgirls.com/devise/ Run these commands in your teminal / commandline.

Add Devise Gem

Open up your Gemfile and add the Devise Gem by adding this line.

Get the most current version here: https://rubygems.org/gems/devise/versions/3.4.1

gem 'devise', '~> 3.4.1'
Install the Devise Gem.
bundle install

Set up Devise in your App

rails g devise:install
Once that runs Devise gives you a set of instructions to follow.

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. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

    config.assets.initialize_on_precompile = false

    On config/application.rb forcing your application to not access the DB or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

    rails g devise:views

=====

Rake devise setup task:

rake devise:setup

This will:

  • drop any existing database
  • create a new database
  • migrate the database
  • create a default user and admin

Phase 3 - Add Bootstrap - Issue #3

"Bootstrap, a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development."

Bootstrap is a framework that makes it easy for a developer to create a nice design for a website or web application. There are predefined css classes for creating common components such as widgets, typography elements, lists, forms, and more. The framework also provides Javascript which makes it easy to create things like modals, popovers, scrollspies, accordions, and more. Their documentation is very thorough, providing example code for most, if not all of the components that Bootstrap provides. ~ Go Tea Leaf

Some possibly helpful Links:

Phase 3 - Add Bootstrap - Issue #3

"Bootstrap, a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development."

Bootstrap is a framework that makes it easy for a developer to create a nice design for a website or web application. There are predefined css classes for creating common components such as widgets, typography elements, lists, forms, and more. The framework also provides Javascript which makes it easy to create things like modals, popovers, scrollspies, accordions, and more. Their documentation is very thorough, providing example code for most, if not all of the components that Bootstrap provides. ~ Go Tea Leaf

Some possibly helpful Links:

bootstrap-sass is easy to drop into Rails with the asset pipeline.

In your Gemfile you need to add the bootstrap-sass gem, and ensure that the sass-rails gem is present - it is added to new Rails applications by default.

gem 'bootstrap-sass', '~> 3.3.4'
gem 'sass-rails', '>= 3.2'

bundle install and restart your server to make the files available through the pipeline.

Import Bootstrap styles in app/assets/stylesheets/application.scss:

// "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"

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

Discuss:

app/assets/javascripts/application.js
//=


Phase 4 - Issue #10

Understand Devise by Using its methods on the Product model

  • Create a Products resource using scaffolding with the attributes name, description, price.

      rails g scaffold name:string description:text price:float
    

This scaffold will create the product controller, model, multiple views and several other files.

=====

Understand the methods which devise gives you and use some of them

  • Require the user to be logged in to access all the Product views
  • Display current_user anywhere.
  • Use one other method
  • Make a comment below (Start using Github to work with the team.)

Kobi's notes on Devise:

Here are my notes on understanding Devise (this was part way through an app I was building). Please read earlier in the week, so that you understand what is going on and PLEASE feel free to email all of us corrections if anything I wrote is off. I'm thinking about publishing some version of this as an article, so any feedback would be greatly appreciated.

Thanks,

Kobi


Learning Devise

BEFORE: Before you used Devise's generator...

Assuming your first resource (aka the model, views & controllers, etc) was called Todo,
such as if you ran: rails g scaffold Todo

then, in your terminal, you run:
rake routes before using Rails Devise Generator.

===========================================================================================

one@one ~/.../practiceapp (master) $ rake routes
   Prefix Verb   URI Pattern               Controller#Action
    todos GET    /todos(.:format)          todos#index
          POST   /todos(.:format)          todos#create
 new_todo GET    /todos/new(.:format)      todos#new
edit_todo GET    /todos/:id/edit(.:format) todos#edit
     todo GET    /todos/:id(.:format)      todos#show
          PATCH  /todos/:id(.:format)      todos#update
          PUT    /todos/:id(.:format)      todos#update
          DELETE /todos/:id(.:format)      todos#destroy
  welcome GET    /welcome(.:format)        static_pages#welcome
     root GET    /                         static_pages#welcome
one@one ~/.../practiceapp (master) $ 

===========================================================================================

AFTER: After you used Devise's generator (by doing something like rails generate devise User). rake routes after using Rails Devise Generator.

NOTE:
In this example, instead of calling the resource/model "User", I am calling it "Baller", so that it is very clear how

  • Used generator: rails generate devise Baller

Now we authenticate with a "Baller" Model (Instead of a "User" Model).

  • Should make it very clear which new routes the Devise generator created.

===========================================================================================

one@one ~/.../practiceapp (master) $ rake routes
                    Prefix Verb   URI Pattern                      Controller#Action
        new_baller_session GET    /ballers/sign_in(.:format)       devise/sessions#new
            baller_session POST   /ballers/sign_in(.:format)       devise/sessions#create
    destroy_baller_session DELETE /ballers/sign_out(.:format)      devise/sessions#destroy
           baller_password POST   /ballers/password(.:format)      devise/passwords#create
       new_baller_password GET    /ballers/password/new(.:format)  devise/passwords#new
      edit_baller_password GET    /ballers/password/edit(.:format) devise/passwords#edit
                           PATCH  /ballers/password(.:format)      devise/passwords#update
                           PUT    /ballers/password(.:format)      devise/passwords#update
cancel_baller_registration GET    /ballers/cancel(.:format)        devise/registrations#cancel
       baller_registration POST   /ballers(.:format)               devise/registrations#create
   new_baller_registration GET    /ballers/sign_up(.:format)       devise/registrations#new
  edit_baller_registration GET    /ballers/edit(.:format)          devise/registrations#edit
                           PATCH  /ballers(.:format)               devise/registrations#update
                           PUT    /ballers(.:format)               devise/registrations#update
                           DELETE /ballers(.:format)               devise/registrations#destroy
                     todos GET    /todos(.:format)                 todos#index
                           POST   /todos(.:format)                 todos#create
                  new_todo GET    /todos/new(.:format)             todos#new
                 edit_todo GET    /todos/:id/edit(.:format)        todos#edit
                      todo GET    /todos/:id(.:format)             todos#show
                           PATCH  /todos/:id(.:format)             todos#update
                           PUT    /todos/:id(.:format)             todos#update
                           DELETE /todos/:id(.:format)             todos#destroy
                   welcome GET    /welcome(.:format)               static_pages#welcome
                      root GET    /                                static_pages#welcome
one@one ~/.../practiceapp (master *) $ 

===========================================================================================

Best review of what the "important" 5-6 Devise methods (helpers)

authenticate_user!
current_user
user_signed_in?
sign_in(@user)
sign_out(@user)
user_session

For our example above, (if Devise allows you to generate different resource names) I'm guessing that the methods would look like this:

authenticate_baller!
current_baller
baller_signed_in?
sign_in(@baller)
sign_out(@baller)
baller_session

NOTE:
authenticate_user! before_filter simply creates a roadblock (checks to see if a user is logged in), before the User hits the controller. If they are logged in (and therefore there is a User, and it is not nil) it allows it to continue to the controller actions. If it is logged out, it redirects to the sign_up page or the login page.


My commit:

Using Devise, authenticate user class 'Baller'   
(1) Add `before_filter authenticate_baller!`,   
  which ensures that a logged in user is available to controller actions   
  (if not logged in redirects to Devise `sign_in page`, if yes logged in,  
we know `current_user` is not nil and redirects to `root_url`) and  
(2) Update `_navigation` partial, so that logged in users  
can log out and logged out users can log in or sign up. 
	-----

authenticate_user! ensures that current_user is not nil.
http://www.gotealeaf.com/blog/how-to-use-devise-in-rails-for-authentication

"The before_filter :authenticate_user! line ensures that current_user is never nil."

=======

Some possibly helpful Links:

https://github.com/plataformatec/devise#controller-filters-and-helpers
https://github.com/plataformatec/devise
http://guides.railsgirls.com/devise/
http://www.rubydoc.info/github/plataformatec/devise/Devise/Controllers/Helpers

http://devise.plataformatec.com.br/

http://www.rubydoc.info/github/plataformatec/devise/frames
http://www.rubydoc.info/github/plataformatec/devise/frames#Starting_with_Rails_

http://rubyonrailshelp.wordpress.com/2014/01/03/creating-user-and-admin-model-using-devise-rails/

https://github.com/danweller18/devise/wiki
http://www.gotealeaf.com/blog/how-to-use-devise-in-rails-for-authentication

Postgres

http://www.jackiejohnston.us/blog/setting-up-user-authentication-with-devise/

Create App, use Devise along the way

http://andreapavoni.com/blog/2013/8/a-rails-4-tutorial-application-for-beginners/#.VHe1Wo-IYb0


Phase - 5? - Install Rspec & Cucumber - Issue #4

gem 'rspec-rails', '~> 3.2.1'

https://rubygems.org/gems/rspec-rails/versions/3.2.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment