Category: Ruby on Rails ++

How to Create a PDF Using Prawn in Ruby on Rails

While working on a client project, I needed to create a PDF for generating invoices on the fly. I wanted something that could be fast and easy to use. As I started searching my way for options, I discovered that there are lot of gems and plugins available in the Rails community for generating PDF.

I found two options which are widely used for generating PDF.

1. Prawn –

2. PDFkit –

So I chose Prawn for the project and believe me adding this to my rails application wasn’t difficult.

1. First thing that we need to do here is, to add the prawn gem inside our gemfile and run the bundle command.

gem ‘prawn’
2. Next we need to create a PDF Mime :: Type inside config/initializers/mime_types.rb – we need to notify rails about the PDF mime type.

Mime::Type.register “application/pdf”, :pdf

(Now when there is a pdf request our application can respond to it. )

3. Then we have to do a couple of changes inside our controller action for which we need to return a pdf version.

This is how my Controller looks like.

class InvoicesController < ApplicationController

  before_filter :authenticate_customer!, :only => [:index, :show]

  def index
    @invoices = Invoice.all_invoices(current_customer)

  def show
    @invoice = Invoice.find(params[:id])
    respond_to do |format|
      format.pdf do
        pdf =, view_context)
        send_data pdf.render, filename:
        type: “application/pdf”

Here you can see inside my show controller that I have created a respond block with html and pdf format. And inside the format.pdf block there is a send_data method we are calling.

send_data pdf.render, filename:
type: “application/pdf”

And what it does is, it sends the data for creating the pdf document. We can have a couple of options passed to this send_data method. Here, I have passed a filename option to name the pdf document, and the type option.

One more option you could use here is to pass the disposition: “inline” after type and what this does is instead of downloading the pdf it would open it in the browser.

Now to work more on the PDF document, we will create a new class.

One good way would be to create a new directory called pdfs inside the apps folder and then creating a new file called invoice_pdf (this is what I have named) and then create a class inside that called InvoicePdf and inherit that with a prawn document.

class InvoicePdf < Prawn::Document


And then inside that we have an initialize method where we called a super method and display the string that we need to show on our PDF.

class InvoicePdf < Prawn::Document

def initialize(invoice, view)
    text “This is an order invoice”

4. In the Invoices controller, inside the show action of the format.pdf block, we have instantiated the InvoicePdf.

pdf =, view_context)
Here, @invoice is the invoice instance that can be accessed inside our pdf document. And view_context is used to access all the view helpers in our PDF document.

5. Restart your application.

And we are ready to go. To add styling to the PDF document, we make changes in the InvoicePdf class.

6. Now inside our InvoicePdf class we need to set @invoice and view_context.

def initialize(invoice, view)
  @invoice = invoice
  @view = view
  text “Invoice #{}”
7. Now we can various methods inside the InvoicePdf class depending on the requirement. For example, to display a logo on the pdf we can have a logo method as defined below.

def logo
  logo_path = “#{Rails.root}/app/assets/images/logo.png”
  image logo_path, :width => 197, :height => 91
and then invoke the logo method inside the initialize method and voila the logo shows up on the pdf.

For more styling options you can refer to –

In the below code snippet, we create a a standard invoice. We can modify it as per our needs.

class InvoicePdf < Prawn::Document

  def initialize(invoice, view)
    @invoice = invoice
    @view = view

  def logo
    logopath = “#{Rails.root}/app/assets/images/logo.png”
    image logopath, :width => 197, :height => 91
    move_down 10
    draw_text “Receipt”, :at => [220, 575], size: 22

 def thanks_message
    move_down 80
    text “Hello #{@invoice.customer.profile.first_name.capitalize},”
    move_down 15
    text “Thank you for your order.Print this receipt as
    confirmation of your order.”,
    :indent_paragraphs => 40, :size => 13

  def subscription_date
    move_down 40
    text “Subscription start date:
    #{@invoice.start_date.strftime(“%d/%m/%Y”)} “, :size => 13
    move_down 20
    text “Subscription end date :
    #{@invoice.end_date.strftime(“%d/%m/%Y”)}”, :size => 13

  def subscription_details
    move_down 40
    table subscription_item_rows, :width => 500 do
      row(0).font_style = :bold
      columns(1..3).align = :right
      self.header = true
      self.column_widths = {0 => 200, 1 => 100, 2 => 100, 3 => 100}

  def subscription_amount
    subscription_amount = @invoice.calculate_subscription_amount
    vat = @invoice.calculated_vat
    delivery_charges = @invoice.calculated_delivery_charges
    sales_tax = @invoice.calculated_sales_tax
    table ([[“Vat (12.5% of Amount)”, “”, “”, “#{precision(vat)}”] ,
    [“Sales Tax (10.3% of half the Amount)”, “”, “”,
    “#{precision(sales_tax)}”] ,
    [“Delivery charges”, “”, “”, “#{precision(delivery_charges)} “],
    [“”, “”, “Total Amount”, “#{precision(@invoice.total_amount) } “]]),
    :width => 500 do
      columns(2).align = :left
      columns(3).align = :right
      self.header = true
      self.column_widths = {0 => 200, 1 => 100, 2 => 100, 3 => 100}
      columns(2).font_style = :bold

  def subscription_item_rows
    [[“Description”, “Quantity”, “Rate”, “Amount”]] + do |subscribe|
    [ “#{subscribe.description} “, subscribe.quantity,
    “#{precision(subscribe.rate)} “,
    “#{precision(subscribe.quantity * subscribe.rate)}” ]

  def precision(num)
    @view.number_with_precision(num, :precision => 2)

  def regards_message
    move_down 50
    text “Thank You,” ,:indent_paragraphs => 400
    move_down 6
    text “XYZ”,
    :indent_paragraphs => 370, :size => 14, style: :bold

Now if we open the browser and navigate to http://localhost:3000/invoices/1.pdf, the invoice would be downloaded.

or we can have a link like this in the views –
<%= link_to “Download invoice”, invoice_path(, :format => “pdf”) %>;

Remember I had pointed out earlier that if we don’t need to download the PDF and just display it in the browser then we can add disposition: “inline” in the send_data method as given below.

send_data pdf.render, filename:
type: “application/pdf”, disposition: “inline” 

Hope this helps all those who are looking for generating PDFs using Prawn. There is lot more to Prawn and I have tried to provide as much information as I could. If there’s something else that you find useful on the topic, please share your thoughts in the comments section.

Rails Girls – Anything They Can Do, We Can Do Better!

Rails Girls Pune

The Genesis

It all started in November 2010, at Helsinki when Linda Liukas and Karri Saarinen, the founders of Kisko Labs decided to empower women by making technology more accessible. Rails Girls was born as a weekend event to open up technology for women and has since flourished in different cities across the world, breaking the online male bastion.

The gem of an idea originated from the simple yet powerful thought of enabling women to build their own web applications – from concept to code. Rails Girls provides women the tools, support, and vocabulary to enter the Internet playground which was essentially built by the boys, for the boys! It helps women bring their ideas to life as they see them.

Global Footprint

And boy! has the movement caught on – from Helsinki to Salvador, Brazil to Osaka, Japan, and our very own Pune, Rails Girls is a rocking event everywhere! The workshop is free and open to all enthusiastic girls and women. Today, there is frenzy among online communities every time an event is organized in their city. The response has been tremendous year after year with scores of women getting initiated into the world of web building.

Local Support

Rails Girls is a not-for-profit operation that is conducted with active support and participation from local sponsors. The latest edition of Rails Girls Pune, for instance, is being organized with the collaboration of local Rails development firms like Idyllic, Big Binary, Josh and ThoughtWorks. The event is scheduled for the 15th of January 2017, at ThoughtWorks’ Pune office. The original venue Idyllic Pune office had to be changed due to the overwhelming response and the registrations had to be closed prematurely, phew! Such is the popularity of the event amongst girls who code or who aspire to code.

What to Expect

Rails Girls Pune is a one day fun-filled workshop with all you needed to know about Ruby on Rails but were afraid to ask! Ruby experts from Idyllic, Big Binary, Josh and ThoughtWorks will coach and mentor the girls in a day-long workshop that promises to live up to the girls’ enthusiasm. If past experience and previous workshops are anything to go by, it’s going to be an exciting Sunday.

What’s Next

The future holds a lot of promise because Rails Girls doesn’t end here at the workshop. With support from Travis Foundation, Rails Girls Summer of Code, popular known as Rails Girls SoC, was initiated. It is a global fellowship program that encourages women to work on Open Source projects and also earn handsomely for their contribution.

More Power to Girls

Rails Girls and Rails Girls SoC are concrete initiatives to get more women to code professionally. They are about helping newcomers and giving them a platform to excel in coding as the career of choice. It has created several success stories with many women finding jobs in the tech arena and some even launching their own start-ups. Now that’s the icing on the cake. One idea, one initiative, one dream, enriching many lives!

We at Idyllic are proud to be associated with the event because we are just as passionate about Ruby on Rails as anybody out there. In fact, we would go a step further and say we are one of the best in the business and some of our clients will vouch for it. Modest we aren’t, but honest we are! And we would like to see more women coding on Ruby. Here’s to more power to Rails and Girls who code!

Standalone JRuby Application with ActiveRecord

This is in continuation to the post I had previously published Standalone Ruby Project with ActiveRecord.There was an application where we were working on and it needed to scale. So, we moved our application to JRuby tuned it for scalability. Thus wanted to share the information.

Let’s convert our existing ruby application to a JRuby standalone application. Actually to do this there are a few steps, involved. Let’s create a new branch from the standalone ruby project we had created. Lets check out the a new branch.

Setup the environment:

Install the bundler gem.


We need to update the dependencies, we will go to, standalone_app.gemspec adding the following dependencies.

spec.add_development_dependency "jdbc-mysql"
spec.add_development_dependency "activerecord-jdbc-adapter"
spec.add_development_dependency "activerecord"

Then add the Ruby Version to the Gemfile. We will just confirm that JRuby is installed correctly.


Lets install our dependencies


Next Steps:

If you are creating an application from scratch please refer the Standalone ruby application with ActiveRecord for getting the rake tasks and application tasks working. Please make you remove the require 'mysql2' from the stanalone_app/Rakefile and standalone_app/lib/standalone_app.rb. Please find the source code on GitHub.

AWS Elastic Beanstalk

AWS Elastic Beanstalk is a PaaS (Platform as a Service) offered from Amazon Web Services with which you can quickly deploy and manage applications in the AWS.

» Services with ElasticBeanstalk : 
1. An Amazon S3 bucket to store environment data and application versions.

a. Environment Data : Elastic Beanstalk creates a new application in which we can create               multiple environments. Each environment has different security group. ElasticBeanstalk has       “environments” bucket in S3 which contain folders according to application’s environment            name and each of it has a compressed code of latest version.
b. Application version : ElasticBeanstalk creates a folder with the name same as of the last commit and uploads files on S3.

2. A load balancer to distribute traffic to the web server(s).

Elastic Beanstalk allows you to create any one of:
a. Load-balancing, autoscaling environment
b. Single-instance environment

3. A security group to allow incoming web traffic.

Elastic Beanstalk creates a default security group. Security group name is visible in the EC2 under Security Groups column.

4. Amazon CloudWatch alarms that notify the Auto Scaling group when the load is low or high.

Amazon CloudWatch alarms help you implement decisions more easily by enabling you to send notifications or automatically make changes to the resources you are monitoring, based on rules that you define.

5. An Auto Scaling group  to adjust the number of servers in response to load changes.

By default, ElasticBeanstalk creates 2 – 4 instances if a user has created an environment with load balancing, autoscaling option.

» Deployment with ElasticBeanstalk
Amazon has given nice document for deployment process and also check this for /.ebextensions configuration

» What happens in the process of Deployment?
1. Elastic beanstalk uploads the code with the latest commit to the S3 in the bucket which has the same name as your application. If the application does not have any new commits, then it considers the files of the last commit. It also updates environment data and application versions.

2. InfraWriteConfig :

It generates –
a) appsourceurl file at /opt/elasticbeanstalk/deploy/configuration/appsourceurl. – S3 url of the latest version of the code.
b) containerconfig file at /opt/elasticbeanstalk/deploy/configuration/containerconfiguration. – contains commands to be executed in the deployment process.

3. InfraWriteApp1 : It (re)creates /opt/elasticbeanstalk/deploy/appsource which contains “source_bundle” file in encrypted format.

4. InfraWriteApp2 : Elasticbeanstalk downloads a manifest file from S3 which contains deployed version number followed by latest version uploaded on S3. These both files are present in environments folder of S3. ElasticBeanstalk also downloads hook files from S3 which contains script files & .sh files to setup environment_variable and do the deployment.

5. Then setup EbExtensionPreBuild :

It adds package and update or create files if you have mentioned in /.ebextensions folder
a. prebuild_0_<application> – it install packages which you have mentioned in /.ebextensions/01packages.config file of ruby app
b. prebuild_n_<application> – creates multiple prebuild tasks depends on the ‘Files’ you have mentioned in /.ebextensions.

6. AppDeployPreHook :

ElasticBeanstalk deploys code in /var/app/deck folder first and does all rails operation. This folder then moved to current. This folder is considered as EB_APP_STAGING_DIR
a. unzip – Unzip folder downloaded from S3.
b. setup_envvars – Get environment_variable and load it to envvar file
c. bundle_install :

i. Load environment_variable
ii. Set ruby-version
iii. Get list of gems (check-for-gem.rb)
iv. move to EB_APP_STAGING_DIR & Do bundle install
v. Change ownership of Gemfile.lock

d. asset_compilation –

i. Load environment_variable
ii. Set ruby-version
iii. get a list of rake tasks (check-for-rake-task.rb)
iv. move to EB_APP_STAGING_DIR & do assets:precompile

e. db_migration –

i. Load environment_variable
ii. Set ruby-version
iii. get a list of rake tasks (check-for-rake-task.rb)
iv. move to EB_APP_STAGING_DIR & do rake:db_migration

f. test_for_puma –

i. Load environment_variable
ii. Set ruby-version
iii. Get a list of gems to be install (check-for-gem.rb) and look for puma gem
iv. update /etc/elasticbeanstalk/has_puma.txt according to availability of gem

7. EbExtensionPostBuild :

It adds container commands from “.ebextensions/05container_commands.config” to create “postbuild_n_<application_name>” and executes it.

8. InfraCleanEbextension :

Remove .ebextensions folder from EB_APP_STAGING_DIR

9. AppDeployEnactHook :

a. Flip Folders

i. move /var/app/current directory to /var/app/current.old
ii. move /var/app/ondeck to /var/app/current
iii. change ownership of /var/app/current folder.
iv. remove /var/app/current.old

b. Restart puma server

10. AppDeployPostHook :

Run .sh files of postdeploy hooks. Delayed_job example with postdeploy script.

Use of Amazon SES in Rails App to Send emails

What is Amazon SES?

Amazon SES is an email platform that provides an easy, cost-effective way to send and receive email using your own email addresses and domains.

Sending Email with Amazon SES using SMTP

You can use Simple Mail Transfer Protocol(SMTP) to send emails by using Amazon SES. You need an Amazon SES SMTP username and password to access the Amazon SES SMTP interface.

To create SMTP credentials:

1. Sign into the AWS Management Console and open the Amazon SES console at

2. In the navigation pane, click SMTP Settings.

3. In the content pane, click Create My SMTP Credentials.


4. In the Create User for SMTP dialog box, you will see that an SMTP username has been filled in for you. You can accept this suggested username or enter a different one. To proceed, click Create


5. Click on Show User SMTP Credentials. Your SMTP credentials will be displayed on the screen; copy them and store them in a safe place. You can also click Download Credentials to download a file that contains your credentials.

After creating your SMTP credentials, open the Verified Senders/Email Addresses screen. Before you can send an email using Amazon SES, you have to own an address or addresses which are going to be used as senders across the SES SMTP mail servers.


Configure mailer with SMTP with rails app:

Add the following code in config/environments/*.rb

Then add following code in mailers/ses_mailer.rb

Note: If your account is in Amazon SES sandbox, then you must also verify the email address of every recipient. For moving out of the sandbox, see Moving Out of the Amazon SES Sandbox.

View: view/ses_mailer/welcome.html.erb

Call Mailer:

You can track your email sending statistics on Sending Statistics of Amazon Console.

Sending emails using aws-ses gem:

1. Add aws-ses to the gem file –

2. Extend ActionMailer in config/initializers/your_config_file.rb, where config_file.rb is the name of the file which contains initialization routines for ses gem:

3. Then set the delivery method in `config/environments/*.rb` as appropriate:

You are now ready to send emails from rails app through Amazon SES. Just make sure you have verified email addresses through which you are going to send the emails and you are out of Amazon SES sandbox. Happy Mailing!!

Charles Proxy: Developer’s & Tester’s Everyday Friend

Charles Proxy is a great tool that will be helpful for everyday use for both Developer & Tester. It can be even helpful for other team members (BA/project lead) when they want to verify particular scenario without depending on deployment from developer’s side.

Charles is a web proxy (HTTP Proxy / HTTP Monitor) that runs on your own computer. Your web browser (or any other Internet application) is then configured to access the Internet through Charles, and Charles is then able to record and display for you all of the data that is sent and received.
In Web and Internet development you are unable to see what is being sent and received between your web browser/client and the server. Without this visibility, it is difficult and time-consuming to determine exactly where the fault is. Charles makes it easy to see what is happening, so you can quickly diagnose and fix problems.
Charles makes debugging quick, reliable and advanced; saving you time and frustration!
Charles works as an intermediate between your machine/device and the internet. Refer to the below image for an overview of it.


The key features of Charles that can be useful in everyday use:

-SSL Proxying – view SSL requests and responses in plain text
-Bandwidth Throttling to simulate slower Internet connections including latency
-AJAX debugging – view XML and JSON requests and responses as a tree or as text
-Edit requests to test different inputs
-Breakpoints to intercept and edit requests or responses
-Repeat requests to test back-end changes
-Basic performance testing
-Remote/local mapping

Viewing response in Charles:

Screen Shot 2016-03-04 at 12.32.31 PM

Charles starts intercepting all the request/response as soon as you launch Charles on your laptop. As seen above, I can see what response I am receiving for the API request I triggered from one of the apps on iPhone simulator.

On the left hand, we can see that Charles clubs all the request under one group of same base URL. On the right-hand side, we can see a response related to the item selected on the left panel.

As we can there are various tabs at the bottom(Headers,Text,Hex,Compressed,Json,Json Text,Raw). These tabs help us to view response in the format we want. Charles auto-detects the type of API response and shows the appropriate tab. For e.g here we have JSON response, hence, JSON and JSON Text tab are visible. If it is not JSON response these tabs will not be visible. Same goes for XML.

Also, on the top, there are various tabs (Overview,Request,Response,Summary,Chart,Notes). These tabs allow viewing specific information related to an entire Http transaction. In a screenshot, we can see Response tab is selected which shows information related to response. Similarly, Request will give information related to a request sent. In overview tab, we can see an entire picture of the transaction related to status code, Request/Response Timing, Request/Response Size.

Enabling SSL Request:

If your connection is Https, you will not be able to directly view response in plain text. To view https data, we need to enable SSL proxying by right clicking on base URL as shown below:

Screen Shot 2016-04-01 at 1.02.25 PM

Also, make sure that Charles certificate is installed on your machine and also on simulators
(if you are using Charles to view simulator traffic for iOS). As seen below, go to help -> Install Charles CA SSL Certificate / Install Charles CA SSL Certificate in iOS Simulators.

Screen Shot 2016-04-01 at 1.09.53 PM

Note: We need to restart the simulator after install SSL Certificate and enabling SSL proxying.

Edit Request/Response:

Now, we know how to use Charles Proxy to view HTTP data. Let us move further to learn how Charles can be useful for editing request and response.

Editing Request:

There can be a different scenario in which you want to edit request.
1) As a tester you want to test API but don’t have mobile application/website available to request specific data but you have a reference Charles logs of similar kind of request, then you can use that request to edit the required parameter and re-execute the request from Charles without having the actual client (mobile app/website) to trigger the request.

For e.g: As seen below, I have Charles log for category 3014. Now I want to use it to trigger a request for category 3016. So, I can right click on 3014 and select Edit option. On selecting Edit, it will generate a new request in editing mode as seen in a second screenshot. Then on the right-hand side, I can alter the URL path from 3014 to 3016 and click on Execute to trigger the request for 3016.

Screen Shot 2016-04-01 at 2.07.11 PM

Screen Shot 2016-04-01 at 2.08.35 PM

2) As a developer, you want to edit the request/response at runtime. For that, you need to intercept the request/response by placing a breakpoint in Charles. Once you set a breakpoint for a specific URL, on next trigger it will break on both request and response. By default, a breakpoint is applied to both request and response. We can change it to intercept for a request or a response only from the breakpoints list based on our requirement.

Screen Shot 2016-04-01 at 2.11.31 PM

Screen Shot 2016-04-01 at 2.14.20 PM

Screen Shot 2016-04-01 at 2.14.34 PM

As seen above, I am setting a breakpoint for product id = 255. So, on the next request for the same product id, it will hit a breakpoint on Charles where you can edit it and execute it. Again on a response, it will halt on Charles side where you can edit the response if you want or execute as it is.

Following screenshot shows Breakpoints Settings where we can add/remove existing breakpoints. Edit a particular breakpoint by double clicking on it.

Screen Shot 2016-04-01 at 3.04.15 PM

Screen Shot 2016-04-01 at 3.16.19 PM

Please note: You will need to edit the response quickly within the time-out duration on your client side. Best practice is to keep edited response ready in the text editor and then just simply replace the entire response once a breakpoint is reached on Charles side.

This feature is very beneficial while developing when we want to test all kind of scenarios for which we don’t have a client interface available ready but we can reproduce it by changing the request/response from Charles side, create error response for observing how the app/client behaves.

Bandwidth Throttling:

Bandwidth throttling is very useful when you want to test the behavior your website/app in slow internet connections. To enable throttling, go to Proxy–>Throttling. Then go to Throttle Settings to set the required speed.

Screen Shot 2016-04-01 at 3.47.07 PM

Screen Shot 2016-04-01 at 3.46.45 PM

Repeat / Repeat Advanced

You can repeat any existing request from the Charles log. This will help to trigger same request to check API response/API testing without dependency of the client interface (website/app).

Repeat advanced can be used to do performance testing related to how much load your server is able to handle concurrent requests and to analyze what amount of requests succeed/fails when increasing the load on a server.

Screen Shot 2016-04-01 at 3.53.33 PM

Screen Shot 2016-04-01 at 3.53.15 PM

As you can see in above screenshot, you can set a number of Iterations and Concurrency which defines how many concurrent requests will be triggered for the number of iterations defined.
So, if you define 10 iterations with concurrency of 100, a total of 10X100 = 1000 request will be fired with 100 concurrent requests at a time.

Remote/local Mapping:

Remote / local is useful for a similar purpose when we referenced previously while discussing Edit Response feature. If we want a response to map from different remote/local URL, we can do so using remote mapping or local mapping. For e.g If we want to test a different version of JS without upgrading in code, we can locally map to load the newer version of JS and test the behavior.
Similarly, we can have local response file or local icon, image,etc that can be used to map response from.

Screen Shot 2016-03-04 at 12.39.15 PM

Screen Shot 2016-04-01 at 4.02.34 PM

Debugging on Android Emulator:

iOS simulator by default gets intercepted via Charles. For Intercepting Android Emulator via Charles, we need few extra efforts.

First, we need local IP address of the machine which can be found from Charles Help menu.

Screen Shot 2016-04-01 at 4.16.12 PM

We need to set this IP address and port number in proxy settings in an emulator.

Genymotion Emulator

Please follow the steps mentioned in screenshots below to enable proxy settings in your emulator.

Screen Shot 2016-04-01 at 4.29.36 PM

Long press on wifi network:

Screen Shot 2016-04-01 at 4.29.42 PM

Click on Modify Network -> In Proxy settings, select Manual

Screen Shot 2016-04-01 at 4.30.47 PM

Enter local Ip address in Proxy hostname and in proxy port enter 8888. Save the settings and now your emulator’s request will go through Charles.

Screen Shot 2016-04-01 at 4.31.02 PM

Android studio Emulator.

For using AVD with Android studio, you need to start the emulator from the terminal using the following command:

./emulator @proxyAvd -HTTP-proxy

Here proxyAvd is my virtual device name.

Connecting Device:


Steps to connect android device is same as android emulator mentioned above.


Go to wifi settings on your device. Scroll down to HTTP Proxy.
Select manual and enter the IP address and port number.


On very first connection with charges from your device, Charles will prompt whether to allow or not the new connection. Choose to allow and your device network traffic will go through Charles.

Make sure Charles SSL certificate is installed on your device. You can install it by visiting Charles website.

Save Charles log:

You can save Charles log by clicking on save icon on the toolbar.


Feel free to contact for any queries or connect on LinkedIn

Ruby on rails Development with Activerecord

If you happen to work with Service Oriented Architectures. There might be many instances where you will end up creating multiple standalone applications. If you are in the Ruby ecosystem you will find that there is no standard structure your application. Like, for instance if you go about creating a standalone Java applications, the structure does appear like:

Most articles that you would come across suggest that, you could give your application some structure with a structure similar to gem. No better than the bundler gem to create your application. We followed the same approach but just added a some more change to the structure. If you are using RVM the first step would be to select the Ruby version and the appropriate gemset.

Next, we will need to install the bundler gem. To check the if bundler gem:

Now we are ready to create our project. This will create your project directory. Now Let’s take a look at the project directory structure that got generated.

Since we want to leverage the niceties of ActiveRecord in the project and add its as a dependency. We will use mysql as our backend. Under the project directory finds the standalone_app.gemspec file add the following dependencies.

It’s time to load the required files in the classpath lets require the gem files. We will require the files at two places. One in the Rakefile where the ActiveRecord rake tasks can run independently. Second in the standalone_app/lib/standalone_app.rb. In the Rakefile we will make the following changes:

You will need to add the following code in the rake file to use the rake db:... tasks in the project.

The code above will include ActiveRecord configurations first setting the ENV for the application, followed by configuring the path of the database configuration file, then pointing the migrations directory standalone_app/db/migrations directory and seeds standalone_app/db/seeds.rb, set the fixtures path, Rest of it is including the active_record rake tasks.

Next, we will get ActiveRecord connections in the application too.


Time to configure the logger. We will create a file called standalone_app/application.rb.

Structure of your project:
Since we will add models to application, we will add the standalone_app/db, add the standalone_app/db/migrate directory to add the migrations. We will also, add standalone_app/db/seeds.rb for the seed data. We will also, add a directory like, standalone_app/app/models to add your models. For the logger, we will create standalone_app/log and then add the standalone_app.log file.

Your business logic can reside in the lib/standalone_app/<files…>

When you are developing a production level application and with active_record. There are a couple nice to haves. One is access to the console like you get in rails.
Let’s create a bin directory
The first file we create is setup. Here are the contents of the file.

To get the console working, we will first add a standalone_app/bin directory to the project. Then inside it we will go about creating a file console.

To access the console
you will just: ./bin/console

When we want to run the application we can start and daemonize the application. Let’s go ahead and create a file: runner_cli

That’s it we are all set. You could find the source code of the project at: Github

WebRTC Opentok in Ruby On Rails for Text chat

This post will take you through adding text chat functionality using Opentok (a WebRTC platform) in Ruby on Rails. OpenTok is a WebRTC platform for embedding live video, voice, and messaging into your websites and mobile apps. Opentok has its own signalling server. We will be using the OpenTok signaling API.
First, we will make the basic setup for using Opentok service. Here we will be using ‘opentok’ ruby gem.

1) Add opentok gem to your Gemfile.

gem ‘opentok’


2) Then create a session that will attempt to transmit streams directly between clients.

Store session id and token somewhere in the database, so that you can use it later on.
Here token gets expired in 30 days(default value). You will need to regenerate after 30 days.

3) Now it’s time to connect to session that we have created above, Add this to your HTML page,

A signal is sent using the signal() method of the Session object. One can receive a signal by listening to a signal event dispatched by session object.
So, All clients who are connected to the same session and listening to same signal type(‘text_chat’ here) will receive a message as soon as someone publishes to channel ‘text_chat’.

Understanding Railtie and Mountable Rails Engine

In earlier versions(Before 3.0) of Rails, we used to build plugins to add new functionality to our application. This would result in a lot of problems during up-gradation of any of the gem/dependencies or Ruby/Rails version. From Rails 3.0, Rails Engine were introduced to prevent these issues. Plugins were deprecated in Rails 4.0.Rails Engine is basically Railtie with some configurations. Before we dive into Rails Engine, let’s understand Railtie first. As per Rails API Doc: Railtie is the core of the Rails framework and provides several hooks to extend Rails and/or modify the initialization process. Every major component of Rails (Action Mailer, Action Controller, Action View and Active Record) is a Railtie. Each of them is responsible for their own initialization. This makes Rails itself absent of any component hooks, allowing other components to be used in place of any of the Rails defaults. Developing a Rails extension does not require any implementation of Railtie, but if you need to interact with the Rails framework during or after boot, then Railtie is needed.

Railtie is the core of the Rails framework and provides several hooks to extend Rails and/or modify the initialization process. Every major component of Rails (Action Mailer, Action Controller, Action View and Active Record) is a Railtie. Each of them is responsible for their own initialization. This makes Rails itself absent of any component hooks, allowing other components to be used in place of any of the Rails defaults. Developing a Rails extension does not require any implementation of Railtie, but if you need to interact with the Rails framework during or after boot, then Railtie is needed.To put in simple words, Railtie is an abstract class, which must be subclassed. It follows Class Based Design (Singleton) pattern. It is responsible for:

To put in simple words, Railtie is an abstract class, which must be subclassed. It follows Class Based Design (Singleton) pattern. It is responsible for:

1. Gluing the components to bootstrap Rails application.
2. Provides rails command line interface and core generator.
3. Provides a way to configure the application components(i.e. instance of subclasses)

The following code snippet from railtie.rb will make it’s function even clearer.

Now, we have understood Railtie, Rails:: Engine nothing more than a Railtie with few configurations set. As a matter of fact, Rails:: Application is also a Rails:: Engine.Let’s say, we want to build two application with similar functionality. One way to do this, to create two application with writing the same code for both applications. But that’s not Rails way. Rails go a mile further to make codes DRY. The better way to do this is to create Rails:: Engine and mount it in both applications. Few really popular examples of Rails:: Engine are: Devise, Spree etc.

Rails:: Engine can be created using the following command:

 ○ ➜ rails plugin new sample_engine --mountable 

It also creates an isolated namespace, so that there is no conflict between core application and Rails:: Engine. i.e. your application can have ‘Users’ model defined as well as your engine. Another option available for Rails:: Engine is –full. 

The above command will generate a number of directory/files similar to Rails new application. An engine can’t run without a Rails application, thus, the –mountable option creates a test/dummy application to run it.

Most of the details to create Rails:: Engine can be found at Rails EdgeGuide. So I’ll skip the steps to create/integrate Rails:: Engine with any Rails application.

Above Rails:: Engine can be mounted on any rails application by adding following route in routes.rb:

Rails.application.routes.draw do
  mount SampleApp::Engine => '/sample_app', as: 'admin'

Let’s analyze how mount of Rails:: Engine works. ActionDispatch::Routing is responsible for mapping the requests to appropriate controller/actions, which in turn is a part of ActionPack.

Below is the snippet of mapper.rb file under ActionDispatch::Routing::Mapper::Base

It’s important to keep in mind that the application should ALWAYS take precedence over its Rails::Engines. A Rails::Engine should be used only to enhance the application instead of changing it completely.

Some Ruby things

The following post consist of some features in ruby that are lesser known to people.

1. alias for ‘.call

2.  Disabling (SSL) Certificate Check from all Gems or Ruby Libraries.

i. Do this only on your local or development environment.
ii. Also the above code only work if the libraries or gem uses ‘Net::HTTP’ API internally,
iii. Tested with HTTParty,Faraday,RestClient not working with Excon (so Excon adapter over Faraday might not work as well).


3. Locking a file using flock.
Firstly, I’ll advise you to read through flock and also this amazing answer by Arjun Shankar.
flock (locking_constant )→ 0 or false

Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.

Locking constants (in class File):

LOCK_EX  - Exclusive lock. Only one process may hold an exclusive lock for a given file at a time.
LOCK_NBL - Don't block when locking. May be combined with other lock options using logical or.
LOCK_SH  - Shared lock. Multiple processes may each hold a shared lock for a given file at the same time.
LOCK_UN  - Unlock.


open(file,'w+') do |file|
  ## lock the file so that no one can use it. 
  read(file_name).each do |row|
    file.puts jsonify(row)



Subscribe To Our Blog

Get access to proven marketing ideas, latest trends and best practices.

Next up home


Lets build cool stuff

Share your contact information & we will get in touch!

I want (Tell us more about your dream project)