Mail Interceptor to Stop Sending Mails From Development Environment

Sometimes it can be pretty frustrating to test out application while receiving a lot of emails from the development environment. Its simply easy to stop sending the emails from development env itself.

Create a custom PreventMailInterceptor in lib folder.

prevent_mail_interceptor.rb
1
2
3
4
5
6
7
class PreventMailInterceptor

  def self.delivering_email(message)
      message.perform_deliveries = false if Rails.env.development?
  end

end

delivering_email method defines whether the mail should be delivered or not.

require the file and include it to the ActionMailer::Base class

action_mailer.rb
1
2
require "#{Rails.root.to_s}/lib/prevent_mail_interceptor"
ActionMailer::Base.register_interceptor(PreventMailInterceptor)

Restart the code and enjoy the application with no more mails.

Happy Coding :)

Using Kiqit to Process the Existing Code to Background Process

Gem Sidekiq provides an easy way to move some long and lengthy time consuming processes to be moved to background and make user experience better. Simply add gem "sidekiq" to Gemfile, run bundle install and create some worker with the long lengthy code.

Before Sidekiq

tasks_controller.rb
1
2
3
4
5
6
7
8
9
class User < ActiveRecord::Base

  def some_time_consuming_task
    .....
    .....
    .....
  end

end

After Sidekiq

some_time_consuming_task_worker.rb
1
2
3
4
5
6
7
class SomeTimeConsumingTaskWorker
  def perform(user_id)
    user = User.find(user_id)
    .....
    .....
  end
end
tasks_controller.rb
1
2
3
4
5
6
7
class User < ActiveRecord::Base

  def some_time_consuming_task
    SomeTimeConsumingTaskWorker.perform_async(self.id)
  end

end

This way the task is moved to be processed in background. Looks pretty simple, cool and easy.

Read on →

What Is the Difference Between Print Puts and P

Print

Print is as suggested prints out any thing given to it out to the terminal.

ruby_irb >  print 'Hello world'
Hello world => nil


Puts

Puts works almost similar to print.

ruby_irb >  puts 'Hello world'
Hello world
=> nil


Read on →

Payment Integration Using Stripe in 5 Easy Steps

Stripe minimal effrst payment gateway to get started. As of official says for stripe

A beautiful, optimized, cross-device payment form, with support for single click payments.

How to Setup

Add gem "stripe" and run bundle install

Create an account on Stripe.com and get API keys and publishable keys. Include them in initializers stripe.rb

stripe.rb
1
2
  Stripe.api_key = "sk_test_xxxxxxxxxxxxxxxxxxxxxxx"
  STRIPE_PUBLISHABLE_KEY = "pk_test_xxxxxxxxxxxxxxxxxxxxxxx"

Include stripe.JS and add stripe meta tag to your application

application.html.erb
1
2
  <%= javascript_include_tag "https://js.stripe.com/v1/", "application" %>
  <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLISHABLE_KEY %>

Create a form, with action target as your back end controller and action where you want to handle. I will explain later why we need controller and action.

payment.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%= form_tag('/custom_path') do |f| %>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"

//Publishable Key From stripe
data-key="<%= STRIPE_PUBLISHABLE_KEY %>"

//Appliation Name
data-name="My Appliation"

//Payment amount(in cents)
data-amount="10000"

//Description for payment
data-description="my custom description"

//Text as will appear on payment button.
data-label='Proceed with payment'

//Users email, who is paying
data-email="<%= user.email  %>"
></script>

<% end %>

This will add a nice looking button to your we page.

Clicking on button will open up a popup

Stripe will handle everything from card validation to authorization over card. When user is successfully authenticated the form will be submitted and we get a token at backend alongwith other form fields value. That is where backend comes into play. The token from above can be used only once. We can use it for

Create a customer

def custom_action
  customer = Stripe::Customer.create(
  :email => 'example@stripe.com',
  :card  => params[:stripeToken]
  )
end

We can save the customer_id for customer create above. Now this customer is registered with stripe. We can charge him anytime.

charge = Stripe::Charge.create(
  :customer    => customer.id,
  :amount      => 10000, # amount in cents
  :description => 'Rails Stripe customer',
  :currency    => 'usd'
)

charge.id will return us the unique transaction id for which we can save.

Directly charge the user

begin
  charge = Stripe::Charge.create(
    :amount => 1000, # amount in cents, again
    :currency => "usd",
    :card => token,
    :description => "payinguser@example.com"
  )
rescue Stripe::CardError => e
  # The card has been declined
end

For more details checkout here and here.

Save Bash History With Timestamps

To check all the commands executed we can simply run history command. This will give us a nice long out put of the all commands executed via bash.

history

bundle install -j  4
gem install passenger
sudo service apache2 restart
passenger-install-apache2-module
sudo subl /etc/apache2/apache2.conf
sudo service apache2 restart
sudo a2ensite codesapling.conf
sudo service apache2 restart
rails s

But at critical times we might need to check the timestamps along with the commands executed on main server machine. To help that we can simply add a variable HISTTIMEFORMAT to bashrc

echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile ; bash

This will add a setting and reload your current bash. Now you can check your history along with time stamps.

history

19.07.14 11:34:19 echo 'export HISTTIMEFORMAT="%d.%m.%y %T "' >> ~/.bashrc
19.07.14 11:36:19 history
19.07.14 11:38:02 bash
19.07.14 11:38:22 history
19.07.14 11:39:08 ls
19.07.14 11:39:16 git add .
19.07.14 11:39:22 git push origin master
19.07.14 11:39:34 history

Websocket - What Are Websocket ?

Web is built all around sending request to server and getting a response back from server, unless browser won’t request an update, the state will remain same. Although. AJAX saves a lot of pages reload and make the web feel more dynamic. But, still we need to make a lot of AJAX request. Which requires either some user interaction or periodic polling to load new data from the server.

This way it creates a hefty load of requests on server for undesired reasons.

WebSocket: Bringing life to Web

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. In layman terms, there is a active connection between server and client.

It is kind of a pipe open at both ends server and client. Both can send any data and would be received at another end.

Getting Started

web_socket = new WebSocket('ws://mywebsocketwebsite.com');

Call back events

Sending Messages.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Send Message
web_socket.send('Ping');

// Sending file as Blob
var file = document.querySelector('input[type="file"]').files[0];
connection.send(file);

// When the connection is established
web_socket.onopen = function () {
  web_socket.send('Ping'); // Send the message 'Ping' to the server
};

// Log errors
web_socket.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

// Calback, for messages from the server
web_socket.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

On server side we can use Ruby, Node.js, Java, Ruby, Python, C++ and all other popular frameworks and languages. In my last post how we can implement in Rails. In next few posts I will show we can build up a complete web socket based environment for chat.

Using Web Socket for Real Time Push Notifications in Rails

Getting started with websocket in rails pretty simple and quick.

  1. Add Gemfile gem to your Gemfile and run the bundle command.
  2. Run generator: rails g websocket_rails:install.
  3. In your application.js do

application.js

application.js
1
2
3
4
5
var dispatcher = new WebSocketRails('localhost:3000/websocket');
dispatcher.bind('tasks.create_success', function(task) {
  console.log('successfully created ' + task.name);
});
      
  1. In controller from where ever the notification has to be sent
tasks_controller.rb
1
2
3
4
5
6
7
8
9
10
class TasksController < ApplicationController

  def create
      @task = Task.new(content: params[:content])
      if @task.save
          WebsocketRails[:tasks].trigger 'create_success', @task
      end
  end

end

This is it, the minimal setup for using websocket is complete. Every time a task is created, a messages is sent to all over the active websocket connections. I have done console.log. After getting data we can process it any ways we want. Such as :

application.js
1
2
3
4
dispatcher.bind('tasks.create_success', function(task) {
  $('.tasks_list').append('<li>' + task.content + '</li>')
});
      

Chat Implementation in Rails Using Private_pub

Private Pub is a Ruby gem which uses Faye to publish and subscribe to messages. For installing just add this to Gemfile of rails application and run Bundle install.

╰─$ rails new chat_private_pub/
╰─$ cd chat_private_pub/
╰─$ echo "2.1.1" >> .ruby-version (optional)
╰─$ echo "chat_private_pub" >> .ruby-gemset (optional)
╰─$ echo "gem 'private_pub'" >> Gemfile (adds gem private_pub to Gemfile)
╰─$ echo "gem 'thin'" >> Gemfile (adds gem thin to Gemfile)
╰─$ rails g scaffold Message content (just to create basic CRUD operations for messaging)
╰─$ rake db:create db:migrate
╰─$ rails g private_pub:install
╰─$ rails s
╰─$ rackup private_pub.ru -s thin -E production (in another tab)

This completes the basic installation. Last command generates two file, one of which is config/private_pub.yml. This stores the configuration for the connection with faye server. Next is add private_pub.js to application.js

//= require private_pub
Read on →

Pluck - a Little Tool to Reduce Database Load

Very often in rails we use something like this

project_ids = current_user.projects.map(&:id)

which gives us an array of project_ids as a result. Behind the scene it is something like

projects = current_user.projects

SELECT `projects`.* FROM `projects` WHERE `projects`.`user_id` = 1

project_ids = projects.map {|p| p.id }

Which means, It fetches all the projects for a user and then loop over all projects to extract the id. Instead we can simply use

project_ids = current_user.projects.pluck(:id)

SELECT `projects`.`id` FROM `projects` WHERE `projects`.`user_id` = 1

Which gives the same output with less load on database. Simple and precise. More.

Update

Pluck can be used to fetch two or more columns now like

users_array = User.pluck(:id, :email)

UUID as Primary Key in Mysql

Last post was about how we can use uuid as primary key in postgres database. In this post going further, uuid is implemented in mysql qit rails.

  • Change the migration file as :
  • 20140517074955_create_users.rb
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    class CreateUsers < ActiveRecord::Migration
      def self.up
        create_table(:users, :id => false) do |t|
          t.string :uuid, :limit => 36, :primary => true
          t.string :name
          t.string :email
          t.string :password_digest
          t.timestamps
        end
      end
    
      def self.down
        drop_table :users
      end
    
    end
    

    Read on →