Home Ruby on Rails Tutorial Rails Tutorial: Building Stock Market Application (1)

Rails Tutorial: Building Stock Market Application (1)

114
0
SHARE
Rails Tutorial Building Stock Market Application2
Rails Tutorial Building Stock Market Application2

Introduction:

In this Ruby on Rails tutorial we will teach you how to build a stock market application quickly with Ruby On Rails. We will make the use of stock_quote gem for this purpose that basically fetches the stock prices from Yahoo API to our app. We will show you that Ruby On Rails is the best framework today for setting up a web application as quickly as possible. 

This will be a two part tutorial. In this post we will focus on setting up our application, adding front end framework, authentication to users and creating required database models. In next post we will add the ability to user to actually track the stock and build the portfolio.

Let’s get started!

Stock Tracking Application:

On your terminal navigate to the working directory and generate the brand new Rails application by executing the command below.

$ rails new stock_tracker

This command will create bunch of files and folders for you.But most of the time we will be working inside the app directory because it contains model, views and controllers. This will also add some of the gems that are required for the application by default. Gems are like plugins in rails world. Now enter into the app directory and run the rails server.

$ cd stock_tracker

$ rails server

The second command starts the lightweight Rails server at localhost:3000. You can navigate to that address in your browser and see the welcome to rails message.

Now I want to create a controller for static pages like home, about, contact. To achieve this execute the following command.

$ rails g controller Staticpages home about contact

This creates a Staticpages controller with home about and contact actions. It also creates some erb(embedded ruby) files to insert our markup code which are inside the views directory. Now we need to map our rails application so that it points to the home action of Staticpages controller as root of our application instead of default welcome screen. Navigate to stock_tracher/config/routes.rb directory and point the home action as root. Your routes file should look similar to this.

Rails.application.routes.draw do

 root ‘staticpages#home’

 get ‘contact’ => ‘staticpages#contact’

 get ‘about’ => ‘staticpages#about’

end

So we have set up the basic foundation of our app. Now we want to integrate the front end framework to our app. In your gemfile add the following line

gem ‘sass-rails’, ‘>= 3.2’

Now run bundle install command to install the gem. Then in your app/assets/stylesheets/application.css and the following line and rename application.css to application.scss.

@import “bootstrap-sprockets”;

@import “bootstrap”;

Remove all the *= require_self and *= require_tree from the file. Move to app/assets/javascripts/application.js and add the line below:

//= require bootstrap-sprockets

Now you must be good to go. If you get any errors or the bootstrap does not seem to render, you can read through the documentation here. To check if bootstrap is applied or not you can inspect the dom and see the sources.

Authentication with devise gem:

Now let’s add devise gem to our application to handle authentication to Users. So in your Gemfile add the following line:

gem ‘devise’

Now run bundle install command to fetch the gem. Now you need to actually install the devise and configure into your application. Execute the following command in your terminal.

$ rails g devise:install

Now let’s generate the User model with f_name, l_name, email properties. To do so we can execute the following command in the terminal.

$ rails g devise User f_name:string l_name:string

This created the migration file for the User model. The migration file should look like this:

class DeviseCreateUsers < ActiveRecord::Migration[5.0]

 def change

   create_table :users do |t|

     ## Database authenticatable

     t.string :email,              null: false, default: “”

     t.string :encrypted_password, null: false, default: “”

     ## Recoverable

     t.string   :reset_password_token

     t.datetime :reset_password_sent_at

     ## Rememberable

     t.datetime :remember_created_at

     ## Trackable

     t.integer  :sign_in_count, default: 0, null: false

     t.datetime :current_sign_in_at

     t.datetime :last_sign_in_at

     t.string   :current_sign_in_ip

     t.string   :last_sign_in_ip

     ## Confirmable

     # t.string   :confirmation_token

     # t.datetime :confirmed_at

     # t.datetime :confirmation_sent_at

     # t.string   :unconfirmed_email # Only if using reconfirmable

     ## Lockable

     # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts

     # t.string   :unlock_token # Only if unlock strategy is :email or :both

     # t.datetime :locked_at

     t.string :f_name

     t.string :l_name

     t.timestamps null: false

   end

   add_index :users, :email,                unique: true

   add_index :users, :reset_password_token, unique: true

   # add_index :users, :confirmation_token,   unique: true

   # add_index :users, :unlock_token,         unique: true

 end

end

Now we need to run the migration so that the actual database table for the User model will be created and ready for working. To run the migration execute the command below:

$ rails db:migrate

Let’s also generate the devise views. Execute the command below:

$ rails g devise views

This command creates the sign in and sign up forms and path. So we don’t need to write the code on our own. If you have some confusion in using devise or you want to change the structure of the app, you can refer to the devise documentation here.

Now, Let’s make our app look beautiful. Let’s add navigation bar, footer to it. Since the navigation and footer will be rendered by our rails application in each page. Let’s create a partial for footer and navigation bar. Basically a partial starts with underscore(_) symbol. Let’s create a new folder /app/views/partial. Inside partial folder create two files _navbar.html.erb and _footer.html.erb.

<nav class=“navbar navbar-inverse”>

 <div class=“container-fluid”>

   <div class=“navbar-header”>

     <a class=“navbar-brand” href=“#”>StockTracker</a>

   </div>

   <ul class=“nav navbar-nav”>

     <li><%= link_to(‘Home‘, root_path) %></li>

     <li><%= link_to(‘About‘, about_path) %></li>

     <li><%= link_to(‘Contact‘, contact_path) %></li>

     <li><%= link_to(‘Log In‘, new_user_session_path) %></li>

     <li><%= link_to(‘Sign Up‘, new_user_registration_path) %></li>

   </ul>

 </div>

</nav>

Let’s create a simple footer now. To do so, create a new file called _footer.html.erb inside the partials directory inside the views. Add the following code.

<div class=“container”>

   <hr>

       <div class=“text-center center-block”>

           <p>- stocktracker.com -</p>

           <br />

             We are the stock tracking company. We love to help you build a portfolio and help you earn much.

</div>

   <hr>

</div>

Now the most important thing we need to render the partial. We need to render the partial in such a way that they are rendered in all pages of our application. To achieve this we need to render those through layouts/application.html.erb . This is like a main file of our front end application. So inside this file it should be

…  

<body>

   <%= renderpartials/navbar.html.erb‘ %>

   <%= yield %>

   <%= renderpartials/footer.html.erb‘ %>

 </body>

Now our authentication system is working and navbar and footer are rendered. Now we need to create a portfolio page for the user . So let’s now create a UsersController and add a action called my_portfolio. First let’s create a route for this. In config/routes.rb add the following line :

get ‘my_portfolio’ => ‘users#my_portfolio’

Now create a controller manually. Create a UsersController.rb under the controllers directory and a view for it under views and create my_portfolio.html.erb. Then your UsersController should look like the following:

class UsersController < ApplicationController

def my_portfolio

end

end

Make sure you have the view template for the action. If not create one manually.Create a file called my_portfolio.html.erb under app/views/users Inside the template insert the following markup.

<h1>Welcome to my portfolio</h1>

You can apply the css rule if you want to make the app look beautiful. This tutorial is basically for learning Ruby On Rails so we are not going to focus on that. Let’s add the link to portfolio to the navbar so users can navigate to it. Update the navbar so that it looks similar to the following.

<nav class=“navbar navbar-inverse”>

 <div class=“container-fluid”>

   <div class=“navbar-header”>

     <a class=“navbar-brand” href=“#”>StockTracker</a>

   </div>

   <ul class=“nav navbar-nav”>

     <li><%= link_to(‘Home‘, root_path) %></li>

     <li><%= link_to(‘About‘, about_path) %></li>

     <li><%= link_to(‘Contact‘, contact_path) %></li>

     <li><%= link_to(‘Log In‘, new_user_session_path) %></li>

     <li><%= link_to(‘Sign Up‘, new_user_registration_path) %></li>

      <li><%= link_to(‘My_portfolio‘,my_portfolio_path) if current_user %></li>

   </ul>

 </div>

</nav>

So the conditional link to the portfolio will render in the navbar if the user exists. Which means there won’t be any portfolio if we don’t have a user or user is not signed in.

Conclusion:

In the next post we will talk about stock model, fetching the stock from API and track the stock.If you are confident to this point, you can start digging deeper.

This is the first part of Ruby on Rails tutorial, for the second part you can go to: Ruby on Rails tutorial Building Stock Market Application Part 2

LEAVE A REPLY

Please enter your comment!
Please enter your name here