How to Add Complex Search Term on Rails?

Today, we will learn how to implement Complex Search Term on Rails, also how to install Bootstrap with Bower and generate fake data with Faker gem.

 

 

Install new project with name “complex_search”-

$ rails new complex_search -d postgresql

Configure database.yml file inside config-

# config/database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  username: postgres # Based on your username
  password: 123456 # Based on your password
  # For details on connection pooling, see rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

Then open your command prompt & write below command for database migration-

$ cd complex_search
$ bundle exec rake db:create
$ bundle exec rake db:migrate
$ bundle exec rails server

Write localhost:3000 to your browser & will show below image-

We just completed the project setup, now needs to setup Bootstrap.

There are three ways to install Bootstrap into a Rails application: as a Ruby Gem, by referencing a publicly available version hosted on a CDN, or by downloading it and storing it within our application’s source.

We’re going to use that latter, assisted by a tool called Bower.
To install Bootstrap using Bower, we’ll first need to install Bower;  then we’ll instruct it to download and install Bootstrap; and, finally, we’ll configure the asset pipeline to make Bootstrap available.
Install Bower

Bower itself as a package manager for the web. It was created by Twitter and is analogous to RubyGems, but manages front-end assets (including CSS frameworks like Bootstrap and JavaScript libraries like Angular). Bower is written in JavaScript, and so it requires a JavaScript runtime in order to work. That means you’ll have to install Node JS.

Once you have Node JS installed, you’ll have access to the npm command-line application. This is a package manager for JavaScript, and we’ll use that to install Bower.
$ npm install -g bower

Then-

# complex_search/Gemfile
gem 'bower-rails'

We can install with bundler.

$ bundle install

We have to create Bowerfile file in the root directory then install Bootstrap.

# complex_search/Bowerfile
asset 'bootstrap-sass-official'

Then-

$ bundle exec rake bower:install

Add bootstrap to our asset pipeline

# complex_search/app/assets/stylsheet/application.css
/*
*= require_tree.
*= require_self
➤ *= require 'bootstrap-sass-official'
*/

We are just done with installing Bootstrap with Bower!

Now we will generate a model called Customer for implementing complex search term-

$ rails generate model Customer first_name:string last_name:string email:string username:string

The migration file created & look like below-

# complex_search/db/migrate/timestamps_create_customers.rb
class CreateCustomers < ActiveRecord::Migration[5.0]
  def change
    create_table :customers do |t|
      t.string :first_name, null: false
      t.string :last_name, null: false
      t.string :email, null: false
      t.string :username, null: false

      t.timestamps null: false
    end

    add_index :customers, :email, unique: true
    add_index :customers, :username, unique: true
  end
end

Then execute following command-

$ rake db:migrate
This will create a “customers” table in database, now generate fake data for implementing search query.
Adding faker gem-
# complex_search/Gemfile
gem 'faker'

Then, we’ll install it the gem-

$ bundle install

After that-

# complex_search/db/seeds.rb
500.times do |i|
  Customer.create!(
    first_name: Faker::Name.first_name,
    last_name: Faker::Name.last_name,
    username: "#{Faker::Internet.user_name}#{i}",
    email: Faker::Internet.user_name + i.to_s + "@#{Faker::Internet.domain_name}")
end

Then execute the above code-

$ bundle exec rake db:seed

We just created 500 fake data (rows) in database!

Building the search UI

$ rails generate controller customers index
# complex_search/config.routes.rb
resources :customers, only: [:index]
# complex_search/app/controller/customers_controller.rb

class CustomersController < ApplicationController
  	def index
  		@customers = Customer.all.limit(10)
  	end
end
# complex_search/app/views/customers/index.html.erb

<h1>Customer Search</h1>
<section class="search-form">
  <%= form_for :customers, method: :get do |f| %>
    <div class="input-group input-group lg">
      <%= label_tag :keywords, nil, class: "sr-only" %>
      <%= text_field_tag :keywords, nil, placeholder: "First Name, Last Name, or Email Address", class: "form-control input-lg" %>
      <span class="input-group-btn">
        <%= submit_tag "Find Customers", class: "btn btn-primary btn-lg" %>
      </span>
    </div>
  <% end %>
</section>

<section class="search-results">
       <h1 class="h3">Results</h1>

  <ol class="list-group">
    <% @customers.each do |customer| %>
      <li class="list-group-item clearfix">
        <h3 class="pull-right">
          <small class="text-uppercase">Joined</small>
          <%= l customer.created_at.to_date %>
        </h3>
        <h2 class="h3">
          <%= customer.first_name %> <%= customer.last_name %>
          <small><%= customer.username %></small>
        </h2>
        
        <h4><%= customer.email %></h4>
      </li>
    <% end %>
  </ol>
</section>

Now create a file inside models called “customer_search_term.rb” and then write following code-

# complex_search/app/models/customer_search_term.rb
class CustomerSearchTerm
  attr_reader :where_clause, :where_args, :order

  def initialize(search_term)
    search_term = search_term.downcase
    @where_clause = ""
    @where_args = {}
    if search_term =~ /@/
      build_for_email_search(search_term)
    else
      build_for_name_search(search_term)
    end
  end

  def build_for_name_search(search_term)
    @where_clause << case_insensitive_search(:first_name)
    @where_args[:first_name] = start_with(search_term)

    @where_clause << " OR #{case_insensitive_search(:last_name)}"
    @where_args[:last_name] = start_with(search_term)

    @order = "last_name asc"
  end

  def build_for_email_search(search_term)
    @where_clause << case_insensitive_search(:first_name)
    @where_args[:first_name] = start_with(extract_name(search_term))
    
    @where_clause << " OR #{case_insensitive_search(:last_name)}"
    @where_args[:last_name] = start_with(extract_name(search_term))

    @where_clause << " OR #{case_insensitive_search(:email)}"
    @where_args[:email] = search_term

    @order = "lower(email) = " + ActiveRecord::Base.connection.quote(search_term) + "desc, last_name asc"
  end

  def start_with(search_term)
    search_term + "%"
  end

  def case_insensitive_search(field_name)
    "lower(#{field_name}) like :#{field_name}"
  end

  def extract_name(email)
    email.gsub(/@.*$/,'').gsub(/[0-9]+/,'')
  end
end

Then modify code in controller file-

# complex_search/app/controllers/customers_controller.erb
class CustomersController < ApplicationController
  PAGE_SIZE = 10
  	def index
  		if params[:keywords].present?
  			@keywords = params[:keywords]
  			customer_search_term = CustomerSearchTerm.new(@keywords)
  			@customers = Customer.where(customer_search_term.where_clause, customer_search_term.where_args).order(customer_search_term.order)
  		else
  			@customers = []
  		end
  	end
end

And that’s all! We have implemented a full & complex search feature on the Rails project.

Happy coding 🙂

 

Setup Ruby on Rails with Windows

How to Setup Ruby on Rails with Windows?

Requirements: Windows OS (10/8/7), Ruby Installer v2.3 or upper

At first, we need to install Ruby on our system.

  • Go to Ruby official site http://rubyinstaller.org/downloads/ then download the latest version of Ruby, then install it on your specific location.
    #=> After installing ruby check the version
    $ ruby -v
    ruby 2.3.1p112 # Or somthing like this
  • Then download Development Kit from the same link as above.
  • Create a folder which called devkit inside the Ruby folder
    Ruby/devkit
  • Extract downloaded devkit inside the devkit folder
  • Run command inside the devkit folder
    #user/Ruby/devkit
    $ ruby dk.rb init
    $ ruby dk.rb install
  • Run command inside the ruby folder “gem install rails”
    Ruby
    $ gem install rails 
    #=> After installing rails check version
    $ rails -v
    Rails 5.0.6
  • Create rails project
    $ rails new project
    #=> After created project then below command
    $ cd project
    $ bundle install
    #=> Configure database
    $ bundle exec rake db:create
    $ bundle exec rake db:migrate
    $ rails server
    
    => Booting Puma
    => Rails 5.0.6 application starting in development on http://localhost:3000
    => Run `rails server -h` for more startup options
    *** SIGUSR2 not implemented, signal based restart unavailable!
    *** SIGUSR1 not implemented, signal based restart unavailable!
    *** SIGHUP not implemented, signal based logs reopening unavailable!
    Puma starting in single mode...
    * Version 3.10.0 (ruby 2.3.1-p112), codename: Russell's Teapot
    * Min threads: 5, max threads: 5
    * Environment: development
    * Listening on tcp://0.0.0.0:3000
    Use Ctrl-C to stop
    
    

     

  • Open the browser. Write “localhost:3000” on address bar and press Enter key.

 

That’s all! Enjoy development/programming with Ruby on Rails 🙂

Setup Scheduled Jobs with Sidekiq, Redis & Ruby on Rails

Sidekiq has been my favorite tool for setting up background processing in Ruby on Rails applications. Mainly I use it for delivering emails, update data inside tables & much more… and it can take a little effort to get up and running every day in exact time on i.e. Heroku.

I have worked with Heroku Scheduler jobs but I have found some issues which explained there documentation that’s why I’m using Sidekiq Scheduler.

Follow below steps:

Run:

gem install sidekiq-scheduler

or you can use your Gemfile
# sidekiq
gem 'sidekiq', '~> 3.3.0'
# sidekiq scheduler
gem 'sidekiq-scheduler', '~> 1'

Then create a folder inside app directory which name “workers”.

app/workers

Create a file inside workers folder like “hello_world.rb”.

#app/workers/helo_world.rb
class HelloWorld
  include Sidekiq::worker
  def perform #=> you can write anything based on your action like 'send_email' or 'newslatter' etc ...
     puts 'Hello World'
  end
end

Now you can go your config file config/sidekiq.yml

:schedule:
  hello_world:
  every: 1m   # Runs once per minute
  class: HelloWorld

Then run

bundle exec sidekiq

Redis is required for sidekiq, install this on your Heroku app then past this on your Procfile same as below-

worker: bundle exec sidekiq -c 5 -v

Then push to your production.

Happy coding 🙂

Users Activity Tracking on Rails

How to enable users activity tracking using the public_activity gem?

On Rails, the public_activity provides easy way for tracking activity for ActiveRecord, Mongoid 3 and MongoMapper models. Simply we have to put records what has been changed or created and that will gives the ability to present those recorded activities to users. Following Github screenshot showing the expected output from the Rails users activity tracking-

 

Following steps we have to follow: (ActiveRecord only)

Step 1:

Add gem 'public_activity' on your Gemfile

Step 2:

Run bundle install

Step 3:

Run rails g public_activity:migration

Then

Run rake db:migrate

Now let’s configure the Model

class Post < ActiveRecord::Base

include PublicActivity::Model

tracked

end

 

Custom activities

@post.create_activity key: 'post.commented_on', owner: current_user

 

View activities

#=> app/controller/notifications_controller.rb

def index

@activities = PublicActivity::Activity.all

end

 

That’s all for tracking all activities.

Happy coding 🙂

Hiring Open – WordPress Developer (Closed)

Salah Software Solution is an award winning software company based in Sylhet, Bangladesh. The company is going to hire new team member for following full-time position-

WordPress Developer – 2

WordPress Developer

Job Responsibilities:

  • Develops web applications, database-driven web pages, web tools and dynamic areas within web pages designed to enhance, sustain and support ideas and vision of the area in compliance with established styles and standards.
  • Integrates user-developed content, and identifies and troubleshoots errors and/or problems with web-based applications.
  • Participates as either project lead or team member in a wide variety of development projects.
  • Remains abreast of technology directions, initiatives and trends within the scope of expertise to provide ideas, guidance, and recommendations.

Desired Qualifications: Experience in

  • WordPress themes and plugins development
  • WordPress website speed optimization
  • Mobile and responsive web design
  • Developing varied web applications using PHP, MySQL, and PostgreSQL
  • Providing technical guidance on WordPress based projects
  • Database design and development on multiple projects
  • WordPress themes, plugins and how they function
  • CSS and standards for consistent user experience of websites
  • Programming languages including PHP, JavaScript, software applications and libraries, database applications, unit testing frameworks, Git, APIs, XML, HTML, and JSON
  • SEO best practices

Other Qualifications:

  • You are fluent in English
  • You are good at utilizing common sense
  • You think positive and happy to assist others
  • You are ready to work minimum 1 year with us
  • You are not lazy and demotivated
  • You are a hard worker and always welcome taking challenges
  • You can work under pressure and meet deadline

Benefits

  • Festival bonus
  • Performance bonus
  • Marriage and new Baby benefits
  • Free lunch and snacks
  • Team outing

Salary Range:

10,000-30,000/-

How to Apply

Please send your updated CV with a cover letter mentioning why we should hire you and expected salary. Also, make sure you added portfolio link on your CV. Email subject should be in following format “WordPress Developer – Your Name – Sep17”. Only send PDF format files to-

Application deadline: 30 September, 2017

Notes: Please only apply if you are experienced with WordPress and can able to do any kinds of WordPress based project work. We encourage you to not apply if your study/degree hasn’t been completed yet. Thank you!

Make simple slider using pure JavaScript

HTML Code:

<img src=”images/slide_image.jpg” id=”SlideImage” alt=”Slide Image” width=”350″ height=”315″ class=”slideImage” />

JS Code:

var slide_image = document.getElementById(“SlideImage”);

var imageArray = [“images/overlook.jpg”, “images/winery_sign.jpg”, “images/lunch.jpg”, “images/bigSur.jpg”, “images/flag_photo.jpg”, “images/mission_look.jpg”];
var imageIndex = 0;

function changeImage() {
     slide_image.setAttribute(“src”,imageArray[imageIndex]);
     imageIndex++;
     if (imageIndex >= imageArray.length) {
       imageIndex = 0;
    }

}

// setInterval is also in milliseconds
var intervalHandle = setInterval(changeImage, 5000);

slide_image.onclick =  function() {
     clearInterval(intervalHandle);
}

Hiring Open – UX/UI Designer (Closed)

Salah Software Solution is an award winning software company based in Sylhet, Bangladesh. The company is going to hire new talents for following full-time positions-

WordPress Developer – 1
Ruby on Rails Developer – 1
UX/UI Designer – 1

UX/UI Designer

Job Responsibilities:

  • Make interfaces that are beautiful and elegant
  • Ensure information is structured in a way that makes the most sense
  • Create interactions that are enjoyable
  • Develop user interaction and interface deliverables, including sketches, wireframes, visual designs
  • Be a champion for users’ needs from requirements gathering through implementation

Desired Qualifications: Experience in

  • Extensive experience designing user experiences across multiple platforms, including responsive web and native mobile.
  • Expert knowledge of Sketch and Adobe Suite, such as Photoshop and Illustrator. Knowledge in prototyping software programs such as Principle or After Effects a plus.
  • Accustomed to validating designs through focus groups, usability testing, and A/B testing, leveraging qualitative and quantitative feedback in the creative process.
  • Experience participating in internal design critiques with the ability to deliver and receive feedback and constructive criticism.
  • Basic understanding of HTML/CSS required, ability to deliver designs in production ready HTML/CSS a plus.
  • Able to multi-task and work in a fluid, fast-paced environment.
  • Obsessively detail oriented with the ability to prioritize design tasks.

Other Qualifications:

  • You are fluent in English
  • You are good at utilizing common sense
  • You think positive and happy to assist others
  • You are ready to work minimum 1 year with us
  • You are not lazy and demotivated
  • You are a hard worker and always welcome taking challenges
  • You can work under pressure and meet deadline

Benefits

  • Festival bonus
  • Performance bonus
  • Free lunch and snacks
  • Team outing

Salary Range:

10,000-30,000/-

How to Apply

Please send your updated CV with a cover letter mentioning why we should hire you and expected salary. Also, make sure you added portfolio link on your CV. Email subject should be in following format “UX/UI Designer – Your Name”. Only send PDF format files to-

Application deadline: 5 May, 2017

Notes: Please only apply if you are experienced with UX/UI design and can able to do any kinds of UX/UI design based project work. We encourage you to not apply if your study/degree hasn’t been completed yet. Thank you

You might also like to visit-

Hiring Open – Ruby on Rails Developer

Hiring Open – WordPress Developer

Hiring Open – Ruby on Rails Developer (Closed)

Salah Software Solution is an award winning software company based in Sylhet, Bangladesh. The company is going to hire new talents for following full-time positions-

WordPress Developer – 1
Ruby on Rails Developer – 1
UX/UI Designer – 1

Ruby on Rails Developer

Job Responsibilities:

  • Develops web applications, database-driven web pages, web tools and dynamic areas within web pages designed to enhance, sustain and support ideas and vision of the area in compliance with established styles and standards.
  • Integrates user-developed content, and identifies and troubleshoots errors and/or problems with web-based applications.
  • Participates as either project lead or team member in a wide variety of development projects.
  • Remains abreast of technology directions, initiatives and trends within the scope of expertise to provide ideas, guidance, and recommendations.

Desired Qualifications: Experience in

  • Ruby on Rails based application development
  • Mobile and responsive web design
  • Developing varied web applications using Ruby on Rails and PostgreSQL
  • Providing technical guidance on web-based projects
  • Database design and development on multiple projects
  • Various kinds of RubyGems and how to use on the Rails app
  • Programming languages including Ruby, JavaScript, software applications and libraries, database applications, unit testing frameworks, Git, APIs, XML, HTML, and JSON

Other Qualifications:

  • You are fluent in English
  • You are good at utilizing common sense
  • You think positive and happy to assist others
  • You are ready to work minimum 1 year with us
  • You are not lazy and demotivated
  • You are a hard worker and always welcome taking challenges
  • You can work under pressure and meet deadline

Benefits

  • Festival bonus
  • Performance bonus
  • Free lunch and snacks
  • Team outing

Salary Range:

10,000-30,000/-

How to Apply

Please send your updated CV with a cover letter mentioning why we should hire you and expected salary. Also, make sure you added portfolio link on your CV. Email subject should be in following format “Ruby on Rails Developer – Your Name”. Only send PDF format files to-

Application deadline: 5 May, 2017

Notes: Please only apply if you are experienced with Ruby on Rails and can able to do any kinds of Rails based project work. We encourage you to not apply if your study/degree hasn’t completed yet. Thank you

You might also like to visit-

Hiring Open – WordPress Developer

Hiring Open – UX/UI Designer

Hiring Open – WordPress Developer (Closed)

Salah Software Solution is an award winning software company based in Sylhet, Bangladesh. The company is going to hire new talents for following full-time positions-

WordPress Developer – 1
Ruby on Rails Developer – 1
UX/UI Designer – 1

WordPress Developer

Job Responsibilities:

  • Develops web applications, database-driven web pages, web tools and dynamic areas within web pages designed to enhance, sustain and support ideas and vision of the area in compliance with established styles and standards.
  • Integrates user-developed content, and identifies and troubleshoots errors and/or problems with web-based applications.
  • Participates as either project lead or team member in a wide variety of development projects.
  • Remains abreast of technology directions, initiatives and trends within the scope of expertise to provide ideas, guidance, and recommendations.

Desired Qualifications: Experience in

  • WordPress front-end and back-end development
  • WordPress website speed optimization
  • Mobile and responsive web design
  • Developing varied web applications using PHP, MySQL, and PostgreSQL
  • Providing technical guidance on web-based projects
  • Database design and development on multiple projects
  • WordPress plugins and how they function
  • CSS and standards for consistent user experience of websites
  • Programming languages including PHP, JavaScript, software applications and libraries, database applications, unit testing frameworks, Git, APIs, XML, HTML, and JSON
  • SEO best practices

Other Qualifications:

  • You are fluent in English
  • You are good at utilizing common sense
  • You think positive and happy to assist others
  • You are ready to work minimum 1 year with us
  • You are not lazy and demotivated
  • You are a hard worker and always welcome taking challenges
  • You can work under pressure and meet deadline

Benefits

  • Festival bonus
  • Performance bonus
  • Free lunch and snacks
  • Team outing

Salary Range:

10,000-30,000/-

How to Apply

Please send your updated CV with a cover letter mentioning why we should hire you and expected salary. Also, make sure you added portfolio link on your CV. Email subject should be in following format “WordPress Developer – Your Name”. Only send PDF format files to-

Application deadline: 5 May, 2017

Notes: Please only apply if you are experienced with WordPress and can able to do any kinds of WordPress based project work. We encourage you to not apply if your study/degree hasn’t completed yet. Thank you

You might also like to visit-

Hiring Open – Ruby on Rails Developer

Hiring Open – UX/UI Designer

How to fix bundle installation error with SSL in Ruby 3?

During bundle installation in Ruby 3, programmers are facing following error-
Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=SSLv3 read server
certificate B: certificate verify failed (https://rubygems.org/gems/rake- 10.4.2.gem)
An error occurred while installing rake (10.4.2), and Bundler cannot continue.
Make sure that `gem install rake -v '10.4.2'' succeeds before bundling.

Note: “Gemfile” located inside your project root folder.

To fix the error and make the update successful, we can use following procedure-
1. Remove secure connection
gem sources -r https://rubygems.org/

2. Add insecure connection
gem sources -a http://rubygems.org/

3. Update rubygems without SSL
gem update --system

4. Remove insecure connection
gem sources -r http://rubygems.org/

5. Add secure connection
gem sources -a https://rubygems.org/

6. Update gems
gem update

Hope this will work for all.