Friday, 27 September 2019

Line Chart

Line Chart 

1.  Add this line to your application's Gemfile:
     # ======= Chart ========
         gem 'chartkick'
         gem 'groupdate'

2.  After run the bundle install 

3.  Sprockets, in app/assets/javascripts/application.js, add:
         //= require chartkick
         //= require Chart.bundle

4.  For View Page :- 
          <%= line_chart User.group_by_day(:created_at).count %>
          <%= line_chart Order.all.group_by_day() { |order| order.created_at    
                }.map{ |date, orders, | [date, orders.size] } 
           %>

Mailer Basics

Action Mailer Basics 

1. Create the Mailer
      rails generate mailer UserMailer

2. Create User:-  (app/mailers/user_mailer.rb)
    class UserMailer < ApplicationMailer
       default from: 'notifications@example.com'
       
       def welcome_email
         @user = user
         @url  = 'http://example.com/login'
         mail(to: @user.email, subject: 'Welcome to My Awesome Site')
      end
    end
 
 3. Create View:-  (app/views/user_mailer/welcome_email.html.erb)
 
        <html>
        <head>
          <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
        </head>
        <body>
          <h1>Welcome to-<%= @user.name %></h1>
          <p>
            You have successfully signed up to gmail.com,
            your username is: <%= @user.name %>.<br>
          </p>

          <p>
            To login to the site, just follow this link: <%= @url %>.
          </p>

          <p>Thanks for joining and have a great day!</p>
        </body>
      </html>
 
4. Add email SMTP settings:- (config/environments/development.rb
      
            config.active_record.dump_schema_after_migration = false
            config.action_mailer.default_url_options = { host: 'localhost:3000'}
            ActionMailer::Base.delivery_method = :smtp
            ActionMailer::Base.perform_deliveries = true
            ActionMailer::Base.raise_delivery_errors = true
             config.action_mailer.smtp_settings = {
               address: "smtp.sendgrid.net",
               port: 587,
               domain: "localhost",
               authentication: "plain",
               enable_starttls_auto: true,
               user_name: "testing.bitterntec",
               :password => "bittern1234"
           }
       config.action_mailer.raise_delivery_errors = true
 
5. Send email:-    UserMailer.welcome_email(@user).deliver
 

 
 

Stripe gem for Using checkout

Stripe gem for Using checkout

1. The first step is adding the Stripe gem to your application’s Gemfile:
     gem 'stripe' 
     gem "figaro"
  
    Then, run bundle install to install the gem.
 
2. Next, generate a new Charges controller:
     rails g controller charges

    The controller does two things:
  1. Shows a credit card form (using Checkout).
  2. Creates the actual charges by calling our API.
3.  Add two actions to the controller:
       
        def new
        end

        def create
          # Amount in cents
          @amount = 500

          customer = Stripe::Customer.create({
            email: params[:stripeEmail],
            source: params[:stripeToken],
          })

          charge = Stripe::Charge.create({
            customer: customer.id,
            amount: @amount,
            description: 'Rails Stripe customer',
            currency: 'usd',
          })

        rescue Stripe::CardError => e
          flash[:error] = e.message
          redirect_to new_charge_path
        end 

4.  Defining the route:-
      So users can access the newly created controller, add a route to it in    
      config/routes.rb:
         resources :charges

5.  Add the following to config/initializers/stripe.rb:

       Rails.configuration.stripe = {
          :publishable_key => ENV['publishable_key'],
          :secret_key      => ENV['secret_key']
        }

      Stripe.api_key = Rails.configuration.stripe[:secret_key]

      # pk_test_WOuxu6ZZPDsPH6NEpxUYKagu00nMNIXrtl
      # sk_test_AULa1uC5wSoUXCfjIexEsTc400FA8BSNpZ


6.  Add the following to config/application.yml:
     
      publishable_key: pk_test_WOuxu6ZZPDsPH6NEpxUYKagu00nMNIXrtl
      secret_key:      sk_test_mjoMHspX73ijf6dnIT4n7j7J00gcIp1dtK

      RAILS_SERVE_STATIC_FILES: true

7.  Creating the views:-  Now create new.html.erb under app/views/charges
      
<%= form_tag charges_path do %>
  <article>
    <% if flash[:error].present? %>
      <div id="error_explanation">
        <p><%= flash[:error] %></p>
      </div>
    <% end %>
    <label class="amount">
      <span>Amount: $5.00</span>
    </label>
  </article>

  <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
          data-description="A month's subscription"
          data-amount="500"
          data-locale="auto"></script>
<% end %>
 
 
8.  Finally, make a create.html.erb view under app/views/charges that shows 
     users a success message:

      
      <h2>Thanks, you paid <strong>$5.00</strong>!</h2>



 
  

FriendlyId

FriendlyId 

It lets you create pretty URLs and work with human-friendly strings as if they were numeric ids.

   # without FriendlyId
     http://example.com/states/4323454

   # with FriendlyId
     http://example.com/states/washington
  
 1. Add this line to your application's Gemfile:
         gem 'friendly_id', '~> 5.2.4' # Note: You MUST use 5.0.0 or greater for  
         Rails   4.0+  And then execute: bundle install
2. Add a slug column to the desired table (e.g. Users)
         rails g migration AddSlugToUsers slug:uniq

3. Generate the friendly configuration file and a new migration
      rails generate friendly_id
      Run the migration scripts  rails db:migrate 
 
4. Edit the app/models/user.rb file as the following: 
     
     class User < ApplicationRecord
        extend FriendlyId
        friendly_id :name, use: :slugged
     end
 
 5. Edit the app/controllers/users_controller.rb file and replace User.find by   
    User.friendly.find

     class UserController < ApplicationController
       def show
         @user = User.friendly.find(params[:id])
       end
     end
 
6. Now when you create a new user like the following:
      User.create! name: "Joe Schmoe"
 
7. You can then access the user show page using the URL http://localhost:3000  
     /users/joe-schmoe.


Schema :-  

create_table "products", force: :cascade do |t|
    t.string "name"
    t.string "description"
    t.integer "price"
    t.string "image"
    t.integer "category_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.float "full_price"
    t.datetime "deleted_at"
    t.index ["deleted_at"], name: "index_products_on_deleted_at"
    t.index ["slug"], name: "index_products_on_slug", unique: true
  end 

Friendly Id Schema 

create_table "friendly_id_slugs", force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name:  "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
  end 
 


     
 
 

will_paginate-bootstrap

will_paginate-bootstrap 

1. For projects using Bundler, add gem 'will_paginate-bootstrap' to your Gemfile (and  
    then run bundle install).

2. Load the Bootstrap CSS in your template.
3. n your view, use the renderer: BootstrapPagination::Rails option with the 
   will_paginate helper, for example:
     
   <%= will_paginate @collection, renderer: BootstrapPagination::Rails %>
 
   <center class="digg_pagination">
     <%= will_paginate @orders, :renderer=> BootstrapPagination::Rails, previous_label: "Older", next_label: "Newer", inner_window: 1, outer_window: 0 %>
   </center> 
 
Links:- https://github.com/bootstrap-ruby/will_paginate-bootstrap 

Pagination Style

/********* Pagination Style ************/

.digg_pagination {
  margin-left: 45%;
  background: #FFFFFF;
  font-size: 1.2em;
  cursor: default;
  /* self-clearing method: */ }
  .digg_pagination a, .digg_pagination span, .digg_pagination em {
    padding: 0.2em 0.5em;
    display: block;
    float: left;
    margin-right: 1px; }
  .digg_pagination .disabled {
    color: #999999;
    border: 1px solid #dddddd; }
  .digg_pagination .current {
    font-style: normal;
    font-weight: bold;
    background: #2e6ab1;
    color: white;
    border: 1px solid #2e6ab1; }
  .digg_pagination a {
    text-decoration: none;
    color: #105cb6;
    border: 1px solid #9aafe5; }
    .digg_pagination a:hover, .digg_pagination a:focus {
     
      }
  .digg_pagination .page_info {
    background: #2e6ab1;
    color: white;
    padding: 0.4em 0.6em;
    width: 22em;
    margin-bottom: 0.3em;
    text-align: center; }
    .digg_pagination .page_info b {
      color: #000033;
      background: #6aa6ed;
      padding: 0.1em 0.25em; }
  .digg_pagination:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden; }
  * html .digg_pagination {
    height: 1%; }
  *:first-child + html .digg_pagination {
    overflow: hidden;
}

Rails Image Upload: Using CarrierWave

Rails Image Upload: Using CarrierWave

     gem 'carrierwave', '~> 2.0'
 
4. Check out this file for some hints on how you can customize your uploader.
    It should look something like this:
    
     class AvatarUploader < CarrierWave::Uploader::Base
        storage :file
     end
 
5. Add a string column to the model you want to mount the uploader by creating 
    a migration:
      rails db:migrate
 
    class User < ActiveRecord::Base
      mount_uploader :avatar, AvatarUploader
    end
 
 
 


 


 

Paranoia Gem for soft delete

Paranoia Gem

Paranoia is a gem that allows you to hide records instead of destroying them. You can recover them later if you want.

Follow these Steps:-

1.  Add the gem to your Gemfile and run bundle:
        gem 'acts_as_paranoid', '~> 0.6.0'
2.  Now you will need to add a migration to have a deleted_at column for the
     models that you want to have the archiving functionality.
        rails g migration add_deleted_at_to_posts deleted_at:datetime:index
     after that you can run rails db:migrate to add the column to the table
3.  Now all you have to do is add the method call acts_as_paranoid to the model  
     that you want the functionality added to, like this:
        class Post < ApplicationRecord
           acts_as_paranoid
        end
4.  https://www.dailysmarty.com/posts/how-to-soft-delete-in-rails( I use  
    this link to complete this task)

Generate a PDF file with wicked PDF gem

Wicked PDF 

1. Add this to your Gemfile and run bundle install:  
       gem 'wicked_pdf'
       gem 'wkhtmltopdf-binary'
  
2. Then create the initializer with  
    rails generate wicked_pdf
 
3. You may also need to add (optional)
       Mime::Type.register "application/pdf", :pdf 
         to config/initializers/mime_types.rb in older versions of Rails.
 
4. Create a PDF link
     <%= link_to  'Create PDF',  order_pdf_path(format: :pdf), class: "btn btn-info btn-sm float-right", 
         data: {toggle: "tooltip", title: "View PDF Agreement"}%>

5. Then update a code in orders_controller.rb file
       def order_pdf
  @orders = current_user.orders
  respond_to do |format|
    format.html
    format.pdf do
    render pdf: "order_pdf",     # Excluding ".pdf" extension.
    show_as_html: params.key?("debug"),  # allow debugging based on url param
    disable_smart_shrinking: true,
    zoom: 0.75
    end
  end
       end

6. Then create a file with Pdf extendion in orders_view_folder(order_pdf.pdf.erb)
  
      <html>
  <head>
  <title>PDF</title>
    <%= wicked_pdf_stylesheet_link_tag "application" %>
    <%= stylesheet_link_tag "http://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"%>
    <%= javascript_include_tag "http://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"%>
  </head>
  <body>  
    <p id="notice"><%= notice %></p>
    <h4 class="order_header text-center">Orders History PDF</h4><br>

    <div class="container">
    <div class="row">
      <table class="table table-hover table-bordered">
        <thead>
          <tr>
            <th>Product Name</th>
            <th>Date&Time</th>
            <th>Address</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Total</th>
            <th>Image</th>
            <th>Order Rating</th>
          </tr>
        </thead>

        <tbody>
          <% if current_user.orders.present? %>
          <% @orders.each do |order| %>
              <tr  style="background-color: cadetblue;">
                <th>ORDER ID: <%= order.id %> (<%= order.user.name %>)</th>
              </tr>
            <% order.cart.cart_items.each do |item| %>
              <% product_id = item.product_id
                product = Product.unscoped.find(product_id) %> 
              <% if product.present? %> 
              <tr>
                <td><%= product.name rescue nil %></td>
                <td><%= Time.now.strftime "%a, %-d %b %Y %I:%M %p" %></td>
                  <% address_id = order.address_id %>
                  <% @add = Address.find_by(id: address_id)%>
                <% if @add.present? %>
                  <td><%= @add.address %>, <%= @add.country%>, <%= @add. post_code%>, <%= @add. district%> </td>
                <% end %>
                <td><%= item.quantity rescue nil %></td>
                <td><%= product.price  || 0.0  rescue nil %></td>
                <td><%= item.quantity * product.price  || 0.0 rescue nil  %></td>
                <td><%= image_tag product.image.url(:thumb) rescue nil %></td> 
                <% if item.product.present? %>
                <td>
                  <div class="btn btn-warning"><a href="/order_review/<%= product.id %>">Review</a></div>
                </td>
                <% end %>
              </tr>
              <% end %>
            <% end %>
              <tr>
                <th></th>
                <th></th>
                <th></th>
                <th><div class="p-2 mb-2 bg-success text-white float-left" style="margin-left: 10%" ><%= order.cart.quantity %></div></th>
                <th></th>
                <th><div class="p-2 mb-2 bg-success text-white  float-left" style="margin-left: 10%" ><%= order.total %></div></th>
              </tr>
          <% end %>
          <% end %>
        </tbody>
      </table><br><br>
    </div>
  </div><br>

      <%= yield %>
    <!-- </div> -->
  </body>
  </html> 
 
 
Links :-1.  https://medium.com/@yazed.jamal/using-wicked-pdf-with-rails-5-3d1a4b0a09ba
             2.  https://github.com/mileszs/wicked_pdf 
 
 

Monday, 9 September 2019

pdf with datatable in rails

pdf with datatable in rails


Step1-  gem 'jquery-datatables-rails', '~> 3.4.0' add in gemfile
Step2-  Add //= require dataTables/jquery.dataTables in application.js file
Step3-  Add  *= require dataTables/jquery.dataTables in application.css.scss file
Step4-    

<script src="http://localhost/assets/js/ZeroClipboard.js"></script>
<table class=" myTable table table-hover" id="example">
  <thead>
    <tr>
      <th>Name</th>
      <th>Description</th>
      <th>Image</th>
      <th>Category</th>
      <th>Quantity</th>
      <th>Price</th>
      <th>Total </th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% if @products.present? %>
    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= product.description %></td>
        <td><%= image_tag product.image.url(:thumb) %></td>
        <td><%= product.category.name %></td>
        <td><input type="number" name=product.id value="1"></td>
        <td><%= product.price %></td>
        <td><%= link_to "Remove",  remove_cart_path(product), data: {method: :delete, remote: true}  %>
        </td>

      </tr>
    <% end %>
    <% end %>
  </tbody>
</table><br>


Step5-    <script type="text/javascript">
                  $('#example').DataTable({
                     dom: 'Bfrtip',
                     buttons: [
                        'copy', 'excel', 'pdf', 'csv'
                   ]
               } );
             </script>
  
 

  Common Git Commands   Take clone of a repository git clone <remote-repository-url> ex: git clone  https://github.com/agricor/RegTech...