Friday, 3 April 2020

Interactor in Rails

What is interactor?


Interactor provides a common interface for performing complex user interactions

An interactor is a simple, single-purpose object.

Interactors are used to encapsulate your application's business logic. Each interactor represents one thing that your application does.

Context

An interactor is given a context. The context contains everything the interactor needs to do its work.

When an interactor does its single purpose, it affects its given context.
Adding context

context.user = user


Example of interactor

class AuthenticateUser
  include Interactor

  def call
    if user = User.authenticate(context.email, context.password)
      context.user = user
      context.token = user.secret_token
    else
      context.fail!(message: "authenticate_user.failure")
    end
  end
end

Monday, 2 March 2020

RuboCop In Rails

RuboCop

A RuboCop is used in Rails best practices and coding conventions. It will make your code in good standard format. it will suggest you the best option to refactor your code in your rails application.


Installation

gem install rubocop-rails


Usage

You can run rubocop in your terminal. You can see the changes in yours console.

$ rubocop

Sunday, 9 February 2020

Create React App in linux system

Creating React Application

To install react run
$  sudo npm install -g create-react-app

Install nde dependencies
$  sudo npm i -g npx
$  sudo apt install nodejs-legacy
$  sudo npm install

Check the below items are installed in your system
$ node -v
$  npx -v
$  npm -v

Install latest version of node
$ sudo npm install -g n
$ sudo n stable

Create the react app
$ npx create-react-app rajfirstreact

Go to the app folder
$ cd rajfirstreact

Run  the react application
$ npm start

You can see your react application running in port 3000
http://localhost:3000

Thursday, 30 January 2020

MailCatcher for Development mail checking in Rails

MailCatcher runs a super simple SMTP server which catches any message sent to it to display in a web interface. Run mailcatcher, set your favourite app to deliver to smtp://127.0.0.1:1025 instead of your default SMTP server, then check out http://127.0.0.1:1080 to see the mail that's arrived so far.
  1. gem install mailcatcher
  2. mailcatcher
  3. Click on http://127.0.0.1:1080
Add the below code in environments/development.rb

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
You can trigger any mail then it will display immediately.

Thursday, 26 December 2019

Importing large data from Xls sheet with background job in rails

In controller need to add the import method with background job.

def import  
new_filename = "#{File.basename(params[:file].original_filename)}_new"
new_filepath = File.join(Dir.tmpdir, new_filename)
FileUtils.cp(params[:file].path, new_filepath)
BackJob.perform_later(new_filepath, 
File.extname(params[:file].original_filename))
redirect_to root_url, notice: 'It take sometime to import'
rescue StandardError => e  puts e.inspect
end

In view index.html.erb add the import button with files.

<%= form_tag import_lists_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>


In BackJob.rb add the import method for storing the data from xls

class BackJob < ApplicationJob
queue_as :default

def perform(fpath, file)
import(fpath, file)
end

def import(filepath, extname)
   spreadsheet = open_spreadsheet(filepath, extname)
    columns = %w[column_one column_tow ]
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[db_columns, spreadsheet.row(i)].transpose]
      obj = ModelName.new
      obj.attributes = row.to_hash.slice(*columns)
      obj.save
   end
end


def open_spreadsheet(filepath, extname)
case extname    
when '.csv'      Roo::Csv.new(filepath)
when '.xls'      Roo::Excel.new(filepath)
when '.xlsx'      Roo::Excelx.new(filepath, file_warning: :ignore)
else raise 'Unknown file type: extname'
end
end
end

Monday, 16 December 2019

How to sort the array of string by alphabetical order with domain based components in ruby?


Input:

array = ["analytics.ramo.com", "ccc.ramo.com", "ccc.test.ramo", "ddd.kumar.ramo.com", "ec2.new.ramo.com", "ramo.com", "test-new.ramo.com", "top-test.ramo.com"] 

Solution:

array.sort_by do |domain|
  parts = domain.split('.').reverse
  parts.unshift(parts.count)
end


Output:

["ramo.com",
 "analytics.ramo.com",
 "ccc.ramo.com",
 "test-new.ramo.com",
 "top-test.ramo.com",
 "ccc.test.ramo",
 "ddd.kumar.ramo.com",
 "ec2.new.ramo.com"]

Monday, 4 November 2019

How to use module as Namespace in ruby?

 Module or Mix-in used as a Namespace in ruby. It is used to avoid collision between two classes.


module Rajkumar
    class Uthayaa
        attr_accessor :email

        def display_email
            puts "my email is #{@email}"
        end
    end
end

module Somu
    class Uthayaa
        attr_accessor :email

        def display_email
            puts "my email 2 is #{@email}"
        end
    end
end

puts raj = Rajkumar::Uthayaa.new
puts raj.email='rajutaya@gmail.com'
puts raj.display_email
puts raj = Somu::Uthayaa.new
puts raj.email='lalalslsls@gmail.com'
puts raj.display_email

How Database index is functioning?


Indexing is a way to optimize the performance of a database by minimizing the number of disk accesses required when a query is processed. It is a data structure technique which is used to quickly locate and access the data in a database.

Indexes are created using a few database columns.
  1. The first column is the Search key that contains a copy of the primary key or candidate key of the table. These values are stored in sorted order so that the corresponding data can be accessed quickly.
  2. Note: The data may or may not be stored in sorted order.
  3. The second column is the Data Reference or Pointer which contains a set of pointers holding the address of the disk block where that particular key value can be found.


Sunday, 3 November 2019

How to install skype on ubuntu 16.04


Kindly run the below commands in terminal for skype installation.

1. Add skype linux repository in your system.

   $ echo "deb [arch=amd64] https://repo.skype.com/deb stable main" | sudo tee /etc/apt/sources.list.d/skype-stable.list

2. To fetch and install Skype public key so that APT package manager verify from repository.

   $ wget https://repo.skype.com/data/SKYPE-GPG-KEY
$ sudo apt-key add SKYPE-GPG-KEY

3. To use https
$ sudo apt install apt-transport-https

4. Update the software source and install skype
$ sudo apt update
 $ sudo apt install skypeforlinux

5. Once installed type skypeforlinux in your application. You can use your skype.

Friday, 11 October 2019

What is difference between display:none & visibility:hidden in CSS?

In CSS display:none & visibility:hidden are mainly used for hiding the tags.


display:none tags will not appear in page at all.

There will be no space allotted in between other tags. Although you can interact with it through DOM.

rajkumar | <p style="display:none;">Style in this tag</p> | rajkumar

OUTPUT for display:none:

rajkumar |  | rajkumar


visibility:hidden tags will not visible.

There will be space allotted in between other tags.

rajkumar | <p style="visibility:hidden;">Style in this tag</p> | rajkumar

OUTPUT for visibility:hidden

rajkumar |                                  | rajkumar. 

Friday, 27 September 2019

Email template design with table cell

Implemented the Email templates with table cell. It will support for all the mailing communications.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
</head>
<body style="margin: 0; padding: 0;font-family: 'Montserrat', sans-serif;background-color: #069C90">
<table cellspacing="0" width="100%" style="padding: 20px 40px;">
    <tr align="center" bgcolor="#069C90">
        <td style="font-size: 30px;color:#fff;font-weight: bold;">
            Hello
        </td>
    </tr>
    <tr align="center" bgcolor="#069C90">
        <td style="font-size: 30px;color:#fff;font-weight: bold;font-style: italic;padding-bottom: 15px;">
            testing
        </td>
    </tr>
    <tr>
        <td>
            <table border="0" cellpadding="0" cellspacing="0" width="100%">
                <tr bgcolor="#f1f1f1">
                    <td style="padding: 10px;color: #6A6A6A;font-size: 20px;" align="center">
                        Thank you for choosing <b style="color: #069C90;font-size: 25px;">testing.</b>
                    </td>
                </tr>
                <tr bgcolor="#f1f1f1">
                    <td style="padding: 10px;color: #6A6A6A;font-size: 20px;" align="center">
                        Finding your new home is our responsibility.
                    </td>
                </tr>
                <tr bgcolor="#f1f1f1">
                    <td style="padding: 10px;color: #6A6A6A;font-size: 20px;" align="center">
                        We wish to full-fill your dream of buying a property at the best price.
                    </td>
                </tr>
                <tr bgcolor="#f1f1f1">
                    <td style="padding: 10px;color: #6A6A6A;font-size: 20px;" align="center">
                        Your hunt for home ends here.
                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td>
                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td>
                                    <table border="0" cellpadding="0" cellspacing="0" width="100%">
                                        <tr style="border-bottom-left-radius: 10px">
                                        <td width="50%">
                                            <img src="img/image_1.jpg" alt="" width="100%" height="auto" style="display: block;" />
                                        </td>
                                        <td width="50%" bgcolor="#f1f1f1">

                                            <a href="#" style="color: #fff;top: 40%;border-radius: 5px;font-weight: bold;font-size: 20px;right: 23%;padding: 20px;background-color: #FF5984;text-decoration: none;">testing</a>

                                        </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>

                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td style="padding: 10px;font-weight: bold;color: #069C90;font-size: 25px;" align="center">
                        More reason to choose from test
                    </td>
                </tr>
               
                <tr bgcolor="#fff">
                    <td style="padding: 10px;font-weight: bold;color: #069C90;font-size: 25px;" align="center">
                        Refer & Earn
                    </td>
                </tr>
                <tr>
                    <td>
                        <table border="0" cellpadding="0" cellspacing="10" width="100%" bgcolor="#E0F3F2">
                            <tr>
                                <td width="50%" align="center" style="border-right: 1px solid #069C90;" bgcolor="#E0F3F2">
                                    <img src="img/image_6.png" height="auto"/>
                                </td>
                                <td width="50%" align="center">
                                    <table border="0" cellpadding="0" cellspacing="10" width="100%">
                                        <tr>
                                            <td style="color: #5B5B5B;font-weight: bold;font-size: 20px;padding: 10px;" align="center">Refer your Friend's to find a property<br>
                                                in rajutaya.blogspot.com</td>
                                        </tr>
                                        <tr style="color: #069C90;font-size: 20px;" align="center">
                                            <td>Maximum <strong style="font-size: 30px;">₹50,000</strong></td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td style="padding: 10px;font-weight: normal;font-style:italic;color: #6A6A6A;font-size: 25px;" align="center">
                        Check out these homes!, which are similar to other<br>
                        listings you've viewed
                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td style="padding: 10px;" align="center">
                        <a href="#" style="text-decoration: none;display: inline-block;padding: 20px;background-color:#FF4576;border-radius: 5px;text-transform: uppercase;color: #fff;font-weight: bold;">Your Dream Home</a>
                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td style="padding: 10px;font-weight: bold;color: #6C6C6C;font-size: 30px;font-style: italic;font-weight: normal" align="center">
                        <strong style="color:#069C90;">1000+</strong> happy customer booked their
                        homes through us
                    </td>
                </tr>
                <tr bgcolor="#fff">
                    <td style="padding: 10px;" align="center">
                        <img src="/img/image_7.png" width="100%" height="auto">
                    </td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td>
            <table align="center" border="0" cellpadding="0" cellspacing="10" width="100%" style="font-size: 25px;" bgcolor="#069C90">
                <tr align="center" style="color: #fff;">
                    <td style="border-right: 1px solid #fff">Chennai</td>
                    <td style="border-right: 1px solid #fff">Bangalore</td>
                    <td style="border-right: 1px solid #fff">Mumbai</td>
                    <td style="border-right: 1px solid #fff">Kolkata</td>
                    <td>Hyderabad</td>
                </tr>
            </table>
        </td>

    </tr>
</table>

</body>
</html>

Saturday, 7 September 2019

Type of Ajax calling

Ajax calling with manual passing the data

<form id='user_info'>
    <input type='text' id='user_id' value='40'>
    <input type='text' id='project_id' value='402'>
<a href='javascript:void(0)' onclick='get_user_info()'></a>
</form>

 
<script type='text/javascript'>
function get_user_info(){
    user_id = $('#user_id').val();
    project_id = $('#project_id').val();
    $.ajax({
    url: '/create_user_information',
    data: {user_id: user_id, project_id: project_id},
    dataType: 'script',
    type: 'POST',
    success: function (data) {
    }
  });
}

</script>


Ajax calling with serialize method

<form id='user_info'>
    <input type='text' id='user_id' value='40'>
     <input type='text' id='project_id' value='402'>
<a href='javascript:void(0)' onclick='get_user_info()'></a>
</form>


<script type='text/javascript'>
function get_user_info(){
    user_id = $('#user_id').val();
    project_id = $('#project_id').val();
    $.ajax({
    url: $('#user_info').attr('action'),
    data: $('#user_info').serialize(),
    dataType: 'script',
    type: 'POST',
    success: function (data) {
    }
  });
}

</script>

Saturday, 31 August 2019

Infinite Scrolling with Ajax in Ruby on Rails.

In controller.rb

Add the pagination with all records in index method

def index
  @listing = Listing.paginate(:per_page=>10, :page=>params[:page])
end

In index.html.erb

Add scrolling script and partial file for appending the display data in index file.
       
 <div class='main'>
 <div id='listing_data'%>
      <%= render partial: 'list_info', locals: {listing: @listing} %>
  </div>


  <input type='hidden' id='next_page_count' value='2'>

  <div class="pagination display_none"></div>
  <div class="display_none">

      <a class="btn view_more" href="#" data-remote="true">Loading</a>
  </div>

 </div>

<script type='text/javascript'>
var queryString = window.location.search;
var pathname = window.location.pathname;
var url = pathname + queryString;

pagination_url = queryString.length > 0 ? url+'&page=<%=@page['next_page']%>' : url+'?page=<%=@page['next_page']%>';
$('.view_more').attr("href",pagination_url);


 var count = $('#
next_page_count').val();
       
 $(window).scroll(function(){
      if  ($(window).scrollTop() == $(document).height() - $(window).height()){
          //if the next page is empty stop ajax calling
            if ($('#next_page_count').val() == ""){
                 return false;
            }else{
                  loadActivity();
            }
       }
    });


  #ajax callling       

  function loadActivity() {
      $('.view_more').click();     
    }
</script> 


In index.js.erb

Add the rendering data here.

$('#next_page_count').val('<%=@page['next-page']%>');

var queryString = window.location.search;
var pathname = window.location.pathname;
var url = pathname + queryString;

pagination_url = queryString.length > 0 ? url+'&page=<%=@page['next_page']%>' : url+'?page=<%=@page['next_page']%>';
$('.view_more').attr("href",pagination_url);


<%if @page['current_page'].to_i == 1 && @page['total_pages'].to_i > 0 %>
 $('#listing_data').html('<%= escape_javascript(render partial: 'list_info', locals: { listing: @listing }) %>');
<%else%>
 $('#listing_data').append('<%= escape_javascript(render partial: 'list_info', locals: { listing: @listing }) %>');
<%end%> 


Whenever scrolling is happening need to call the next page with ajax calling.if params[:next_page] is null stop the ajax calling.




Monday, 26 August 2019

Find the missing elements and display the sorted elements in ruby?

Inputs:
a=[1,2,3,4,5,6,7,8,9,10]
b=[1,2,4,5,6,7,8,9,10]

missing_elements = []
for i in a.min..a.max
    missing_elements.push(i) unless b.include?(i)
end

missing_elements.each do |m|
    b.insert(a.index(m),0)
end
p a
p b

for i in 0..a.length-1
puts "#{a[i]}-#{b[i]}"
end

OUTPUT:
1-1
2-2
3-0
4-4
5-5
6-6
7-7
8-8
9-9
10-10

How to find the missing elements in an array using ruby?

Input: a= [3, 4, 5, 6, 7, 15]

min_element  = a.min
max_element = a.max
new_missing_elements = []

for i in (min_element..max_element)
   new_missing_elements.push(i) unless a.include?(i)
end

print new_missing_elements

OUTPUT:

=>[8, 9, 10, 11, 12, 13, 14]

Friday, 2 August 2019

Class method calling in ruby?

Class methods:
We can call the class method by using class name.

class MyClass
   def self.my_method
     puts 'i am class method'
  end
end

 
 
MyClass.my_method
output=>
i am class method

Tuesday, 9 July 2019

How to find a given number is prime or not in ruby?

def check_prime n
    (2..n-1).each do |no|
         return false if n % no == 0
    end
    true
end

Tuesday, 2 July 2019

How to multiply the array elements in ruby?

a= [1,2,3,4,5,6,7,8]

Scenarios 1:
a.reduce(:*)

Scenarios 2:
b=1

a.each do |e|
  b=b*e
end


Factorial program using ruby

def factorial_no
  yield
end

n=gets.to_i
factorial_no do
  (1..n).reduce(:*)
end


Monday, 17 June 2019

How to Find the sum of total elements in an array using ruby?

a= [1,2,3,4,54,656,76,43,560]

Solution 1:

a.inject(&:+)

output: =>1399

Solution 2:

b = 0
a.each do |e|
  b+=e
end
b

output: =>1399

Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...