Google Recaptcha in Ruby on Rails without using any gem.

used ruby 2.3.5p376 ,  Rails 5.1.4,  At localhost ip: ,

Note: Application sated using command :  rails server -p 3000
Accessed website using on :
todo before coding:

search: google recaptcha , The select the 1st option or directly visit

click: get reRECAPTCHA , fill following form

click submit you get google credential for client side page and server side as shown in the below 2 images:

server side:


Now  moving to rails code :

    1. New rails app.
      rails new recaptch_app - d mysql
    2. Create a scaffold from terminal
      rails g scaffold album title author
    3.  Routing in recaptch_app/config/routes.rb
      root to: 'albums#new'
    4.  create  a custom library  in  recaptch_app/lib/recaptcha_v2.rb
      require 'net/https'
      require 'open-uri'
      class RecaptchaV2
        def initialize(response)
          @params = {}
          @params[:response] = response
          @params[:secret] = '6LfOPUMUAAAAAEleBb1iS-pHTypHchGWumylXm3v'
          @params[:remoteip] = '' 
        def verify!
          url = URI.parse('')
          req =
          con =, url.port)
          con.use_ssl = true
          res =    con.start {|http| http.request(req)}
          res_array = JSON.parse(res.body)
          result = res_array['success']
    5. For controller recaptch_app/app/controllers/albums_controller.rb
      def create
          @album =
          recaptcha =['g-recaptcha-response'])
          result = recaptcha.verify!
          respond_to do |format|
            if result &&
              # if verify_recaptcha(model: @user) &&
              format.html {redirect_to @album, notice: 'Album was successfully created.'}
              format.json {render :show, status: :created, location: @album}
              format.html {render :new}
              format.json {render json: @album.errors, status: :unprocessable_entity}

      params[‘g-recaptcha-response’]  is received on form submit:
      6. File: recaptch_app/app/views/albums/_form.html.erb

7. Include library directory inside recaptch_app/config/application.rb

config.autoload_paths += %W(#{config.root}/lib)

Done! result


Adding New Store in magento


Step 1 : Create a new category with anchor as yes in display setting.

Step 2: Go to Setting>> Store Management >> Create new website, store , assign root category, store view.

Step 3: Go to Settings >> Configuration >> Click on Web >> Select the Store from drop down >> Enter new base url . >> Save

Step 4:  Set Virtual host: D:xamppapacheconfextrahttpd-vhosts.conf If Xampp

<VirtualHost *:80>
DocumentRoot “D:/xampp/htdocs/teststore”

Step 5: Setup host file “C:WindowsSystem32driversetchosts”

Step 6:Setup htaccess file

SetEnvIf Host MAGE_RUN_CODE=test
SetEnvIf Host MAGE_RUN_TYPE=website
SetEnvIf Host ^ MAGE_RUN_CODE=test
SetEnvIf Host ^ MAGE_RUN_TYPE=website

Here MAGE_RUN_TYPE can be store or website value

MAGE_RUN_CODE should be the unique code that you have saved while creating new store website in mange store.

All done, Assign products to website your new store with different domain is ready in use

View original post 1 more word

Create Mongo DB Service for windows


Configure a Windows Service for MongoDB Community Edition


Open an Administrator command prompt.

Press the Win key, type cmd.exe, and press Ctrl + Shift + Enter to run the Command Prompt as Administrator.

Execute the remaining steps from the Administrator command prompt.


Create directories.

Create directories for your database and log files:

mkdir c:datadb
mkdir c:datalog

Create a configuration file.

Create a configuration file. The file must set systemLog.path. Include additional configuration optionsas appropriate.

For example, create a file at C:Program FilesMongoDBServer3.4mongod.cfg that specifies both systemLog.path and storage.dbPath:


Install the MongoDB service.


Run all of the following commands in Command Prompt with “Administrative Privileges”.

Install the MongoDB service by starting mongod.exe with the --install option and the -configoption to specify the previously…

View original post 117 more words

Add custom fields in user model created using devise

  1. After generating the custom views using devise gem using:
rails generate devise:devise users

2. Adding custom fields inside users model

rails generate migration addNameToUser name:string

rake db:migrate

3. Now add the custom field inside the view i.e: views/users/registrations/edit.html.erb

div class="field">
  <%= f.label :name %> <br/>
  <%= f.text_field :name, autofocus: true %>

4. To render customer views created in views/users/ make change inside the devise configuration file: ie. /config/initializers/devise.rb are change the following :

config.scoped_views = true

5.  Now you have to make changes inside controller/application.rb to allow the fields :

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters, if: :devise_controller?


  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
    devise_parameter_sanitizer.permit(:account_update, keys: [:name]) 


Run ruby scripts inside command prompt in windows

First you need to install ruby inside you windows system. I am assuming you have have already installed it.In place command prompt you can install ComEmu from

1. Now create a folder inside you drive and place your ruby scripts inside it.


mkdir ruby_scripts

cd ruby_scripts

Simplest Ruby scripts is:

#!/usr/bin/env ruby

print "Enter name? "
name = gets.chomp 
puts "your #{name}!"

and save this script in sample.rb inside ruby_scripts folder. Now, run the ruby script using

ruby sample.rb

Rails App with confirmation and login in one go

  1. Build new rails app with Mysql database.
rails new app -d mysql

2.  create an welcome controller with index method with its view index.html.erb 

rails g controller welcome index

Open routes file in config/routes.rb and set :

get 'welcome/index'
root 'welcome#index'

3. Add Devise gem in the Gemfile

gem ‘devise’

now look the devise gem version install that will be install on your system.

bundle list  do the after step 4

this command will version of the gems. you have to mention the devise version in you gemfile now, because after few years the devise gem version will be changed and the remote gem will be update. Now if you project get transferred to the new server and the new developer will run a bundle install command he will get the error which will take hours to resolve or he will have to check the version of the devise installed on the old server and then mention the same in the gemfile or the best practise is keep updating your/client project according to the latest gems version by bundle update.

4. Install Devise gem

bundle install

Install Devise , this will generate the necessary configuration files of Devise like devise.rb inside config/initializers/devise.rb

rails generate devise:install

5. Now multiple instruction will appear on command prompt add the following line inside config/environments/development.rb

config.action_mailer.default_url_options = { host: localhost, port: 3000} also define default URL options config.action_mailer.delivery_method = :smtp config.action_mailer.default_url_options={:host => ‘localhost’ , :port => ‘3000’} Inside app/views/layouts/application.html.erb set notice and alert messages above <%= yield %>

<p class="notice"><%= notice %></p>

<p class="alert"><%= alert %></p>

6. Generate user model with Devise gem

rails generate devise user

This creates the necessary field required by user model to use devise gem authentications

7. Edit edit the generate migration file inside db/migrations/******_devise_create_users.rb  and commencement the following lines. 

## 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

8. Now, inside welcome/index.html.erb place the link:

<%= link_to 'User sing_in', new_user_session_path %>


If you are using window you will receive this error

TypeError: Object doesn't support this property or method <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

To resolve this remove  //= require_tree . from application.js inside app/assets/javascripts/application.js

and remove  *= require_tree .  from app/assets/stylesheets/application.css

Now Login , Sign_up,  will start working fine without any error’s.

9. Now we can populate our welcome/index.html.erb

<h1>Welcome to ruby Deise</h1>
<% if user_signed_in? %>
    <%= link_to 'Edit Profile' , edit_user_registration_path ,:class=>'navbar-link' %>
<%= link_to 'Log out', destroy_user_session_path, method: :delete , :class=>'navbar-link' %>
<% else %>
    <%= link_to 'Sign in', new_user_session_path,:class=>'navbar-link' %> 
    <%= link_to 'Sign  up', new_user_registration_path , :class=>'navbar-link'%>
<% end %>

Now, configuring Devise mailer to send the necessary emails in while registration and forget password

10. Edit environment/development.rb add the following configuration:

config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host:'localhost',port:'3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
    user_name:      '',
    password:       'xyz@123',
    domain:         'localhost:3000',
    address:       '',
    port:          '587',
    authentication: :plain,
    enable_starttls_auto: true
I have mentioned the user_name ,password and host directly instead of it we can 
store these variable inside our ~/.bash.rc
export EMAIL=
export PASSWORD = password 
and use ENV['EMAIL'] ,ENV[PASSWORD] inside development.rb inplace of hard coding the value's.
11. Inside model user.rb add :confirmable

class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,:confirmable

12. To generate the views which we are already using inside views/devise:
 rails g devise:views

Directories will be as:

13. Overriding mailer views and generating view inside views/users

rails generate devise:views users
Directories will be as 
if you came across this error: 
ActionView::Template::Error (undefined method `new_confirmation_path' for #<#<Class:0xa78d298>:0xa78c758>):

14.Then, Generate the confirmation views run and reconfirm that you have added :confirmable inside user model

rails generate devise:views confirmable

15. Finally run the pending migrations and change the current environment to development rake

db:migrate RAILS_ENV=development

Note: Please use a newly created gmail id or that id which you have not secured other mailer will work fine and it will show you that it is sending email but confirmation emails will not be sent.

15. Create user controller

rails generate user controller

and proceed.