Create your own scheduler within 10 minutes with Rails and dhtmlxScheduler

Today I am going to show you how to create a Google-like scheduler with your Rails application. Here we are going to  use dhtmlxScheduler. It is a Javascript event calendar. Intuitive drag-and-drop interface allows the end users to quickly manage events and appointments in different views: Day, Week, Month, Year, Agenda, Timeline, etc. For more info regarding dhtmlx click here.

Step- 1: Let’s first create a new Rails application for our scheduler

$ rails new my_scheduler

nishant@nishant26: ~_058

Step- 2: Create  a ‘Home’ controller

$ rails g controller home index

Selection_059

Step – 3 open config/routes.rb and replace as following

get ‘home/index’

with

root ‘home#index’

Step – 4 Start Rails server now and test it in your browser with http://localhost:3000

$ rails s

Selection_060

Step- 5 Now download the dhtmlxScheduler. Download open source from standard edition box. Now unzip the file

Add following files to vendor/assets/javascripts
codebase/dhtmlxscheduler.js
codebase/ext
codebase/locale

and following files to vendor/assets/stylesheets

codebase/dhtmlxscheduler.css
codebase/dhtmlxscheduler_classic.css
codebase/dhtmlxscheduler_flat.css
codebase/dhtmlxscheduler_glossy.css

Then we need to create an assets folder in the public directory and copy following files there.

codebase/imgs
codebase/imgs_dhx_terrace
codebase/imgs_flat
codebase/imgs_glossy

Now open config/initializers/assets.rb and add our newly added css and js to asset precompile settings:

Rails.application.config.assets.precompile += %w( dhtmlxscheduler.css )
Rails.application.config.assets.precompile += %w( dhtmlxscheduler.js )

Step – 6: Open views/layouts/application.html.erb and include include dhtmlxscheduler.js and dhtmlxscheduler.css

<%= stylesheet_link_tag ‘dhtmlxscheduler’, media: ‘all’, ‘data-turbolinks-track’ => true %>

<%= javascript_include_tag ‘dhtmlxscheduler’, ‘data-turbolinks-track’ => true %>

Step- 7: Now open your newly created home/index.html.erb.It will display our scheduler.

Now we add a container for our scheduler and initialize our event calendar

<div id=“scheduler_here” class=“dhx_cal_container” style=‘width:100%; height:800px;’>
<div class=“dhx_cal_navline”>
<div class=“dhx_cal_prev_button”>&nbsp;</div>
<div class=“dhx_cal_next_button”>&nbsp;</div>
<div class=“dhx_cal_today_button”></div>
<div class=“dhx_cal_date”></div>
<div class=“dhx_cal_tab” name=“day_tab” style=“right:204px;”></div>
<div class=“dhx_cal_tab” name=“week_tab” style=“right:140px;”></div>
<div class=“dhx_cal_tab” name=“month_tab” style=“right:76px;”></div>
</div>
<div class=“dhx_cal_header”>
</div>
<div class=“dhx_cal_data”>
</div>
</div>

<script>
scheduler.init(“scheduler_here”);
</script>

Step- 8: Restart your server and check your browser at http://localhost:3000

Selection_061

Step- 9: So dhtmlxSheduler is initialized and we may proceed to further settings. Let’s create a model for an event.  Run the following command

$ rails g model Event start_date:datetime end_date:datetime text:string

Run database migration
$ rake db:migrate

Step- 10: Now open config/routes.rb and add another route for data loading

get “home/data”, to: “home#data”, as: :data

step : 11:
Open controllers/home_controller.rb and add ‘data’ action to it.

def data
  events = Event.all

  render json: events.map {|event| {
    id: event.id,
    start_date: event.start_date.to_formatted_s(:db),
    end_date: event.end_date.to_formatted_s(:db),
    text: event.text
}}
end

step -11
Add another route to perform antoher db relate action

get “home/db_action”, to: “home#db_action”, as: :db_action

def db_action
  mode = params[“!nativeeditor_status”]
  id = params[“id”]
  start_date = params[“start_date”]
  end_date = params[“end_date”]
  text = params[“text”]

  case mode
  when “inserted”
    event = Event.create :start_date => start_date, :end_date => end_date,     :text => text
    tid = event.id

  when “deleted”
    Event.find(id).destroy
    tid = id

  when “updated”
    event = Event.find(id)
    event.start_date = start_date
    event.end_date = end_date
    event.text = text
    event.save
    id = id
  end
  render :json => {
    :type => mode,
    :sid => id,
    :tid => tid,
  }

end

Step – 12- To save the changes in scheduler we need to use DataProcessor. Open app/views/home/index.html.erb.

var dp = new dataProcessor(“<%= db_action_path %>”);
dp.init(scheduler);
dp.setTransactionMode(“GET”, false);

Now add following lines to your index.html.erb script tags:

scheduler.config.xml_date=”%Y-%m-%d %H:%i”;
scheduler.init(“scheduler_here”);
scheduler.load(“<%= data_path %>”, “json”);
var dp = new dataProcessor(“<%= db_action_path %>”);
dp.init(scheduler);
dp.setTransactionMode(“GET”, false);

If you want to use a post request for changing the data in your database, then you need to specify Transaction Mode dataProcessor = POST. Moreover, you need to change the corresponding route to:

post “home/db_action”, to: “home#db_action”, as: :db_action

And you need to add following line in your controllers/application_controller.rb

protect_from_forgery with: :null_session

instead of

protect_from_forgery with: :exception

Step- 15: Finally we are ready to see the result: run your server

$ rails s

Selection_063

The whole source code is availabe at my git repository.

All set! Now, go to your browser and start scheduling your day!!

Have a happy coding!!

Introduction to some Interesting gems!

Hi Guys, Yesterday I was reading an open source project code(errbit). Reading an open source project code improve your coding capabilities. It enhances your technical knowledge and code vocabulary. You may found some new coding patterns as well.

Today I am going to share some interesting gems which I found in that project. I have also created a demo app using some of those gems.

Here I listed out some of those gems:

1. actionmailer_inline_css :

Gmail doesn’t support <style> or <link> tags for HTML emails. Other webmail clients also have problems with <link> tags.
This means that CSS must be inlined on each element, otherwise the email will not be displayed correctly in every client.

Inlining CSS is a pain to do by hand, and that’s where the premailer gem comes in.

This actionmailer_inline_css gem is a tiny integration between ActionMailer and premailer.

2. decent_exposure :

Rails controllers are the sweaty armpit of every rails app. This is due, in large part, to the fact that they expose their instance variables directly to their views. This means that your instance variables are your interface… and that you’ve broken encapsulation.

decent_exposure makes it easy to define named methods that are made available to your views and which memoize the resultant values. It also tucks away the details of the common fetching, initializing and updating of resources and their parameters.

I have created a demo app to understand the use of this gem. Please refer my demo for more brief introduction.

3. Htmlentities :

HTMLEntities is a simple library to facilitate encoding and decoding of named (&yacute; and so on) or numerical ({ or Ī) entities in HTML and XHTML documents.

4. Hipchat :

HipChat is a group and private chat, file sharing and integration application. Here is the HipChat HTTP API Wrapper in Ruby with Capistrano hooks. You can find API documentation for HipChat here.

5. Flowdock :

Flowdock is a team collaboration app for desktop, mobile and web. Here is the Ruby gem for Flowdock.  You can refer API for Flowdock here.

6. Quiet_assets :

Most of the time while debugging in console we get frustrated with unnecessary logging statements of assets. This gem helps to mute assets pipeline log messages. Quite useful!

Setting up a subdomain that points to an external public IP(Or Hosted somewhere else like Digital Ocean)

If you have already a working site, hosted on a specific domain and you want to add a sub domain that points to a site hosted on a different VPS, then you need to add your public IP to point to that site.

For example I have a domain registered on Bluehost and I want to create a sub-domain that points to my site hosted on Digitalocean. To do so follow this steps.

First of all you must have credentials to login to the cPanel of your site.

Login to your cPanel and search for advance DNS zone editor option

image02

Click on this option and you will find list of available domain with their IPs and sub-domains if any.

image00

 

  • Create a record, Add your subdomain name here, then your TTL value. Then your site type  which you want to point.
  • select A if your are pointing to an external public IP which must be static. and it must be IPv4 if it is IPV6 then select AAAA CNAME if you are pointing to a domain name or sub-domain.
  • Now in Address field add the address or domain name.
  • Then click Add Record button.

Done! Now wait for at least 24 to 72 hours. It will take this much time to get effect. This time is not sure.

If you want to edit or cancel a detail then you can select and update or cancel.

image01

 

Running Django application on Vagrant

Vagrant is useful to create and configure lightweight, reproducible, and portable development environments.

Here I am going to show you how to setup Vagrant on Ubuntu 14.04 and how to up and running a Django application on it.(You can try same with Rails application)

Follow these steps.

1. Install Virtualbox:
    $ sudo apt-get install virtualbox

2.  Install Vagrant
    $ sudo apt-get install vagrant

3. Preparing Django application for VM:

Go to application home directory and Initializes the it to be a Vagrant environment aware.
    $ vagrant init

This will create an initial Vagrantfile if one doesn’t already exist. You might have to override some of the default configurations. Here is the whole config file from my local setup.

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant::Config.run do |config|
# Base box to build off, and download URL for when it doesn’t exist on the user’s system already
config.vm.box = “ubuntu/trusty32”
config.vm.box_url = “https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-i386-vagrant-disk1.box&#8221;

# As an alternative to precise32, VMs can be built from the ‘django-base’ box as defined at
# https://github.com/torchbox/vagrant-django-base , which has more of the necessary server config
# baked in and thus takes less time to initialise. To go down this route, you will need to build
# and host django-base.box yourself, and substitute your own URL below.
#config.vm.box = “django-base-v2.2”
#config.vm.box_url = “http://vmimages.torchbox.com/django-base-v2.2.box&#8221; # Torchbox-internal URL to django-base.box

# Boot with a GUI so you can see the screen. (Default is headless)
# config.vm.boot_mode = :gui

# Assign this VM to a host only network IP, allowing you to access it
# via the IP.
# config.vm.network “33.33.33.10”

# Forward a port from the guest to the host, which allows for outside
# computers to access the VM, whereas host only networking does not.
config.vm.forward_port 8000, 9000

# Share an additional folder to the guest VM. The first argument is
# an identifier, the second is the path on the guest to mount the
# folder, and the third is the path on the host to the actual folder.
config.vm.share_folder “project”, “/home/vagrant/dfportal_shared”, “.”

# Enable provisioning with a shell script.
# config.vm.provision :shell, :path => “etc/install/install.sh”, :args => “myproject”
end

4. Start Vagrant
    $ vagrant up

5. After successful login, go to root directory and run following command:
     $ cd home/vagrant/mydjango_apps_shared

You should be able to find manage.py there.

The mydjango_apps_shared is the shared directory between your machine and VirtualMachine. Quite Amazing!!

Install required packages for Django Application:

6. Install python package installer on VM

    $ sudo apt-get install python-pip

7. Install Django using pip:

     $ sudo pip install django

8. Install required packages:

    $ sudo pip install -r requirements.txt

9. Setup Mysql DB in VM

    $ sudo apt-get install mysql-server

10. Then connect to mysql and create a DB for your application
   $ mysql -u root -p
   Enter password:
      > create database my_db
      $ exit

11. Synchronize the database state with the current set of models and migrations
        $ python manage.py syncdb

12. To load fixtures run
     $ ./manage.py loadfixtures

13. Up and Running
    $ python manage.py runserver 0.0.0.0:8000

Now start the browser and hit localhost:9000 or 127.0.0.1:9000 and your application works!!!

If you can’t see the page, just look back to Vagrant file and check config.vm.forward_port settings to exactly know which port the VM is listening and forwarding.

Importance of writing Test cases in an existing Rails Application

Hey guys!!

In my first article, I going to introduce you the importance of writing test cases(either with Rspec or minitest) with existing Rails Application and why one should write it?

Once you have created your Rails application and now you are quite excited with your bunch of code, files and directories. The only thing that you are missing now is Test cases??

Actually It’s not TDD(Test Driven Development) but It’s the way to learn TDD.

There are three important benefits by writing test cases:

1. You practice about thinking all cases and all possible conditions.
After writing enough tests, you will become aware of where is the possibility of breaking of methods, And as soon as you start TDD you can use this skill  to write robust tests to handle all possible cases of your application.

2. You get habituated with well structured tests.
Once you have done enough practice for writing tests, now you can apply different design patterns for structuring those tests.

3. You find the tests which are hard to  test.
As soon as you get more familiar, you will understand that which part of application is very hard to test and which part of the application is very easy to test. This will provide you the strength of analysis for future estimation of any project.

4. Tests are also very important while migration.
If your rails application has been written all possible test scenarios, then you can upgrade your rails application easily. You can upgrade it to any latest stable version.

Ease into TDD

Whenever you are testing your application,instead of clicking around in the browser to reproduce it, it better two write some cases.

Here is the flow of writing test cases:
a. Write a failing test
b. Run the test,
c. Fix the bug
d. Run the tests
e. Refactor tests

TDD is always preferable to write new rails application.(if you have enough time)

In my next post I will show you how to write tests? and how to pass them.

Have A Happy Coding!!!