Google documents vs Microsoft word

0

Today I tried google document in order to replace Microsoft word. It’s been 4 years since I have stopped using Microsoft Products other than doing some University project or when I need to use C# or SQL Server 2012 for data warehousing. At beginning when I tried google drive, I thought today is last day for Microsoft office on my Mac laptop. But unfortunately there are so many features missing in google documents and its a long way before I can replace Microsoft office for google drive. Here are list of feature that is missing in google documents.

1. No proper way to have table of content. I know you can insert table of content but it is not very professional and there is no page number in table of content. There is only one default style and we don’t have many choice.

2. It doesn’t check grammar errors for me.

3. If I put multiple white spaces between words than google document doesn’t inform me.

5. If I start my sentence will lower case “i” than google document doesn’t inform me.

6. It doesn’t have templates for cover sheet.

7. Reference is not possible other than few add-ons.

8. It doesn’t support feature of showing synonymous for certain words. English is not my first language, so I use this feature a lot to improve documentations while doing university assignments.

I know google have introduced add-ons functionality for google documents but currently there are not many of them available. May be in future there will be lot of add-ons available and one day I can completely replace Microsoft word but until then I am going to stick to Microsoft word.

Advertisements

Testing Controller with Rspec

0

Rspec is awesome when it comes to testing. In this post I am going to post code for simple controller and than I am going to post some code to test this controller. Both code and test can be refactored further but I am not refactoring them at this moment so that they will be easier to read. Once our test will pass then we will try to refactor it.

First of all, here is my code of controller which have seven default actions.


class PostsController < ApplicationController
  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def create
    post = Post.new(params[:post])
    if post.save
      flash[:notice] = "Post created sucessfully."
      redirect_to root_path
    else
      flash[:error] = "Post creation failed."
      render :new
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def update
    post = Post.find(params[:id])
    if post.update_attributes(params[:post])
      flash[:notice] = "Post upaded sucessfully."
      redirect_to root_path
    else
      flash[:error] = "Post update failed."
      render :edit
    end
  end

  def destroy
    Post.find(params[:id]).destroy
    flash[:notice] = "Post deleted sucessfully."
    redirect_to root_path
  end
end

Now below in my test for this controller. While testing controller we should focus mainly on three things:
1. We should check if instance variable has been set properly for view or not?
2. We should check what template response is going to render or which action its going to redirect.
3. Finally, If flash notice and flash errors has been properly set or not.

We don’t need to test anything more than this into controller. We should not test if our create method is going to increase database count or not. These type of tests doesn’t belong in controller test.

require 'spec_helper'

describe PostsController do
  let!(:first_post)  { Post.create(:title => "Test Title", :body => "Test Body")}

  describe "GET 'index'" do
    before { get :index }

    it "assigns @posts" do
      expect(assigns(:posts)).to eq([first_post])
    end

    it "renders the index template" do
      expect(response).to render_template("index")
    end
  end

  describe "GET 'show'" do
    before { get :show , :id => first_post.id }

    it "assigns @post" do
      expect(assigns(:post)).to eq(first_post)
    end

    it "renders the show template" do
      expect(response).to render_template("show")
    end
  end

  describe "GET 'new'" do
    before { get :new }

    it "assigns @post" do
      expect(assigns(:post)).to be_a_new(Post)
    end

    it "renders the new template" do
      expect(response).to render_template("new")
    end
  end

  describe "POST 'create'" do
    context "when valid" do
      before { post :create, :post => {:title => "Test Title", :body => "Test Body"} }

      it "will redirect to root path" do
        expect(response).to redirect_to(root_path)
      end

      it "will set flash[:notice]" do
        expect(flash[:notice]).to be_present
      end
    end

    context "when invalid" do
      before { post :create, :post => {:title => "Test Title", :body => ""} }

      it "will render new template" do
        expect(response).to render_template("new")
      end

      it "will set flash[:error]" do
        expect(flash[:error]).to be_present
      end
    end
  end

  describe "GET 'edit'" do
    before { get :edit, :id => first_post.id }

    it "assigns @post" do
      expect(assigns(:post)).to eq(first_post)
    end

    it "renders the edit template" do
      expect(response).to render_template("edit")
    end
  end

  describe "PUT 'update'" do
    context "when success" do
      before { put :update, :post => {:title => "Update Title", :body => "Update Body"},:id => first_post.id }

      it "will redirect to root path" do
        expect(response).to redirect_to root_path
      end

      it "will set flash[:notice]" do
        expect(flash[:notice]).to be_present
      end
    end

    context "when not success" do
      before { put :update, :post => {:title => "", :body => ""},:id => first_post.id }

      it "will render new template" do
        expect(response).to render_template("edit")
      end

      it "will set flash[:error]" do
        expect(flash[:error]).to be_present
      end
    end
  end

  describe "DELETE 'destroy'" do
    before { delete :update, :id => first_post.id }

    it " will redirect to posts path" do
      expect(response).to redirect_to root_path
    end

    it "will set flash[:notice]" do
      expect(flash[:notice]).to be_present
    end
  end
end

Refactored Version of Rspec

Below is refactored version of Rspec, its smaller in size than previous test.

require 'spec_helper'

describe PostsController do
  let!(:first_post)  { Post.create(:title => "Test Title", :body => "Test Body")}

  describe "GET 'index'" do
    before { get :index }

    it { expect(assigns(:posts)).to eq([first_post]) }
    it { expect(response).to render_template("index") }
  end

  describe "GET 'show'" do
    before { get :show , :id => first_post.id }

    it { expect(assigns(:post)).to eq(first_post) }
    it { expect(response).to render_template("show") }
  end

  describe "GET 'new'" do
    before { get :new }

    it { expect(assigns(:post)).to be_a_new(Post) }
    it { expect(response).to render_template("new") }
  end

  describe "POST 'create'" do
    context "when valid" do
      before { post :create, :post => {:title => "Test Title", :body => "Test Body"} }

      it { expect(response).to redirect_to(root_path) }
      it { expect(flash[:notice]).to be_present }
    end

    context "when invalid" do
      before { post :create, :post => {:title => "Test Title", :body => ""} }

      it { expect(response).to render_template("new") }
      it { expect(flash[:error]).to be_present }
    end
  end

  describe "GET 'edit'" do
    before { get :edit, :id => first_post.id }

    it { expect(assigns(:post)).to eq(first_post) }
    it { expect(response).to render_template("edit") }
  end

  describe "PUT 'update'" do
    context "when success" do
      before { put :update, :post => {:title => "Update Title", :body => "Update Body"},:id => first_post.id }

      it { expect(response).to redirect_to root_path }
      it { expect(flash[:notice]).to be_present }
    end

    context "when not success" do
      before { put :update, :post => {:title => "", :body => ""},:id => first_post.id }

      it { expect(response).to render_template("edit") }
      it { expect(flash[:error]).to be_present }
    end
  end

  describe "DELETE 'destroy'" do
    before { delete :update, :id => first_post.id }

    it { expect(response).to redirect_to root_path }
    it { expect(flash[:notice]).to be_present }
  end
end

Testing Routes using Rspec

1

Most Rails developers don’t test their routes separately, they write controller test and try to catch every possible scenarios in a controller test. Today I learned how to test route separately. I have created seven routes using

  resources :posts

Here are lists of routes thats been created by above code.

  rake routes

     root        /                         posts#index
    posts GET    /posts(.:format)          posts#index
          POST   /posts(.:format)          posts#create
 new_post GET    /posts/new(.:format)      posts#new
edit_post GET    /posts/:id/edit(.:format) posts#edit
     post GET    /posts/:id(.:format)      posts#show
          PUT    /posts/:id(.:format)      posts#update
          DELETE /posts/:id(.:format)      posts#destroy

Now below I have written tests for each routes


require 'spec_helper'

describe "Routes" do
  describe "PostsController" do
    it "routes get index" do
      expect(:get => "posts").to route_to(
        :controller => "posts",
        :action => "index"
      )
    end

    it "routes get new" do
      expect(:get => "posts/new").to route_to(
        :controller => "posts",
        :action => "new"
      )
    end

    it "routes get show" do
      expect(:get => "posts/1").to route_to(
        :controller => "posts",
        :action => "show",
        :id => "1"
      )
    end

    it "routes post create" do
      expect(:post => "posts").to route_to(
        :controller => "posts",
        :action => "create"
      )
    end

    it "routes get edit" do
      expect(:get => "posts/1/edit").to route_to(
        :controller => "posts",
        :action => "edit",
        :id => "1"
      )
    end

    it "routes put update" do
      expect(:put => "posts/1").to route_to(
        :controller => "posts",
        :action => "update",
        :id => "1" 
      )
    end

    it "routes delete destroy" do
      expect(:delete => "posts/1").to route_to(
        :controller => "posts",
        :action => "destroy",
        :id => "1"
      )
    end    
  end
end

If you want to write test for un routable routes than here is code for that

   resources :posts, :except => [:show]
  
    it " does not route to get show" do
      expect(:get => "posts/1").not_to be_routable
    end

You can place your routes tests inside controller folder but I created a new folder name routing. If you name your folder anything other than routing that you have to add a type to your describe like this

describe YourController, :type => :routing do
...
end

OR

describe YourController, :type => :controller do
...
end

Script to clone git repo or update git repo

0

Yesterday there was question on Stackoverflow.com how to clone a git repo using a script or update a git repo if it already exists in a local machine. Here is my quick solution that i wrote using ruby. There are many things that can be improved in this script but I am not going to improved them now. We can add a rescue block when we are trying to communicate with github.

REPO_PATH = '/Users/full_path/to_repo'
REPO_NAME = 'xxx'
GITHUB_URL = 'git@github.com:xxx/xxx.git'


def change_dir_to_repo
  Dir.chdir(REPO_PATH)
  puts system('pwd')
end

def git_repo_exists?
  if Dir.exists?(REPO_NAME)
    puts "Git repo #{REPO_NAME} exists."
    update_git_repo
  else
    puts "Git repo #{REPO_NAME} does not exists."
    clone_git_repo
  end
end

def clone_git_repo
  system("git clone #{GITHUB_URL}")
  puts "Done"
end

def update_git_repo
  puts "Changing directory to #{REPO_NAME}"
  Dir.chdir(REPO_NAME)
  puts "Changing branch to master"
  system('git checkout master')
  puts "updating git repo"
  system('git pull')
  puts "Done"
end

change_dir_to_repo
git_repo_exists?

Password Generator in Ruby

0

This is the simple password generator that i wrote in Ruby. Firstly i am creating array of characters, numbers and symbols and then i am putting all those arrays in sigle place called secret(which is array). While I am joining all these arrays together, I am calling “Shuffle” method on them so that every time secret array have elements in different order. Once my secrete array is ready then I am generating password from secrete array. First of all i am using shuffle method on secrete array and then i am taking first 15 elements from secrete array using “take” method. I could have also used range(0..14) but I prefer using “take” method and finally I am joining all those 15 elements together using “join” method. Its very simple and useful method. This method will generate random password when ever its called.

def password_generator
  secrete = []
  char_array = ("a".."z").to_a
  num_array  = (0..9).to_a
  symbol_array = %w[! @ # $ % ^ & * ( ) _ - + = { [ } ] : ; " ' < , > . ? /]

  secrete.concat(char_array.shuffle)
  secrete.concat(num_array.shuffle)
  secrete.concat(symbol_array.shuffle)

  password = secrete.shuffle.take(15).join
end

Outputs

$j4″kzp8;}.@)hu
qkxu#'{6&i,>r3?
l5,v%a};t’31$?w
?>w4&c@o(}){+#2
^h[w<cg’x3y*6a$

Markdown Language

0

Last week in my job I was asked to update few documents on Github about setting up developers environment. When i looked at the readme.md document on Github, it looked like a HTML document but when i opened the file on text editor it was not written in HTML. At that time i learned something about markdown language. Markdown language is easy to read and easy to write plain text format, which can be easily converted to HTML. In fact its so easy that it can be learned within 30 min without any previous knowledge of HTML. Below are few of the tags used in markdown language.

Markdown Heading 1
# Heading 1

Html Heading 1

<h1>Heading 1</h1>

Markdown Heading 2
## Heading 2

Html Heading 2

<h2>Heading 2</h2>

Markdown Heading 3
### Heading 3

Html Heading 3

<h3>Heading 3</h3>

Markdown bold
**bold text**

Html bold

<strong>bold text</strong>

Markdown italics
*italics text*

Html italics

<em>italics text</em>

Markdown bold and italics
***bold and italics***

Html bold and italics

<strong><em>bold and italics</em></strong>

Markdown blockquote
> this is a quote.

Html blockquote

<blockquote>this is a quote.</blockquote>

Markdown Ordered list

1. first item
2. second item
3. third item

Html Ordered list

<ol>
	<li>first item</li>
	<li>second item</li>
	<li>third item</li>
</ol>

Markdown unordered list

* first item
* second item
* third item

For unordered list using markdown language we can use either “*”,”+” or “-” symbols.

Html unordered list

<ul>
	<li>first item</li>
	<li>second item</li>
	<li>third item</li>
</ul>

Markdown Strikethrough
~~this is strikethrough.~~

Html Strikethrough


<del>this is strikethrough</del>

Markdown Table

Column 1 | Column 2 | Column 2
---------|----------|---------
Row 1 | Row 1 | Row 1
Row 2 | Row 2 | Row 2
Row 3 | Row 3 | Row 3

Html Table

<table>
<tr>
   <th>Column 1</th>
   <th>Column 2</th>
   <th>Column 3</th>
</tr>

<tr>
   <td>Row 1</td>
   <td>Row 1</td>
   <td>Row 1</td>
</tr>

<tr>
   <td>Row 2</td>
   <td>Row 2</td>
   <td>Row 2</td>
</tr>

<tr>
   <td>Row 3</td>
   <td>Row 3</td>
   <td>Row 3</td>
</tr>
</table>

There are many other tags available for markdown language which can be easily found on internet.

Editor for Markdown

There are many editors found for Mac,Windows and Linus which can convert markdown tags to Html tags. However I am using MOU on Mac. MOU can convert markdown language to html format as soon as you type them on MOU screen.It helps you see the output of what you have written. Currently MOU is on beta version and can be download for free from this link.MOU also allows to convert .md file into pdf file or convert .md(markdown) into html file.It comes with different templates, including template for Github.

Ruby Visibility : public, private and protected

1

Now a days I have started learning Ruby and/ Rails because my new job requires these languages. While programming in Ruby, it feels so natural and syntax of Ruby is much cleaner compared to other programming languages that i did in the past. However there are few confusing things in Ruby when you come from other programming languages such as Java, C#, C++ etc. One of those things are methods visibility in Ruby. In Ruby every methods are public by default.

class Foo

  def say_hello
  	puts "Hello World"
  end

  def say_bye
  	puts "Good Bye"
  end

end

now in above code both the methods “say_hello” and “say_bye” are public by default so if i create object of Foo class and call methods “say_hello” and “say_bye” it will work as expected


foo = Foo.new
foo.say_hello    # will print "Hello Wolrd"
foo.say_bye      # will print "Good bye"

Now lets make method “say_bye” to private, in Ruby to make any method private we write keyword private and then define methods underneath the word private. Any method written after word “private” will all be private

class Foo

  def say_hello
  	puts "Hello World"
  end

  private

  def say_bye
  	puts "Good Bye"
  end

end

foo = Foo.new
foo.say_hello    # will print "Hello Wolrd"
foo.say_bye      # Error: calling private method

So far everything is working as expected. We know that we can’t call method “say_bye” directly on foo object because “say_bye” is private method but we can call method “say_bye” inside “say_hello” method. So far nothing new. Now lets create another class called “Bar” which will inheritance from “Foo” class


class Bar < Foo

  def say_bar
  	puts "I am bar."
  end

end
bar = Bar.new
bar.say_bar     # will print "I am bar."

Now from langauges like Java, we know that during inheritance, child class will inherit public and protect methods from parent class. But in Ruby it’s different, in Ruby child class also inherit private methods as well. To demonstrate this concept lets call private method “say_bye” of “Foo” class inside “Bar” class

class Bar < Foo

  def say_bar
  	puts "I am bar."

  	say_bye
  end

end
bar = Bar.new
bar.say_bar      # will print "I am bar."
                 # Good Bye"

If we see the result we print out “I am bar” and “Good Bye”.This shows that in Ruby child class inherite private method from parent class. You can call those private methods inside your class but you can not call them on object. Code show below will not work because you are trying to invoke private method directly on the object.

bar = Bar.new
bar.say_bye   # Error     

Another surprising feature of Ruby which i haven’t seen in languages like Java is, even you make your methods private, you can still force it and call it as public. Ruby understands that’s its programmers responsibility to know what they are doing. It allows method to be private but if programmers still want to invoke private methods then Ruby won’t stop programmers from doing so. We can invoke private methods by using “:send”.


foo = Foo.new
foo.say_hello       # will print "Hello Wolrd"
foo.send(:say_bye)  # will print "Good Bye"


bar = Bar.new
bar.say_bar         # will print "I am bar."
bar.send(:say_bye)  # will print "Good Bye"