Practical Web Programming

Thursday, December 19, 2013

git: Merge master to feature_branch Often to Minimize Conflicts

One of the best way to avoid conflicts (or large unmanageable conflicts) is to merge master often to develop or whatever feature branch you are working on. This way, you will integrate all the changes made to master (by other developers or you) to the current branch as you progress. Here's an easy way to do it:

$ git checkout feature_branch
$ git pull origin master

The first command makes sure you are on the right branch, and the second one fetches the changes in origin/master repo and merge into the current branch. Take note that if you omit origin master from the second command, it will try to fetch and merge origin/feature_branch - not what you want to do here.

Monday, November 18, 2013

How to Connect to a Server via SSH


ssh -p 800 user@kabalweg.com

where:
kabalweg.com = is the server
user = the user defined in that server
800 = connection port to that server

Thursday, November 14, 2013

How to scp (Secure Copy) File from a Server to Local Machine

The console command below will copy the file from the remote server to the desktop using the same filename.


scp root@remote_server:/var/lib/backup/server_backup.gz ~/Desktop


where: 
root = the user to that server
remote_server = host entry in you ~/.ssh/config file

Wednesday, November 06, 2013

How to Load Your Own jQuery Library When CDN is Down

It's always a good practice to load libraries like jQuery your web applications from CDN (Content Delivery Network). But sometimes (though rare) CDN goes down. The code below makes that you have jQuery loaded in events like this.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">if (typeof jQuery == 'undefined') {  document.write(unescape("%3Cscript src='Scripts/jquery.2.0.0.min.js' type='text/javascript'%3E%3C/script%3E"));
}</script>

Wednesday, October 23, 2013

Automatically Run Tests with Guard

Step by step guide:

1) Edit the Gemfile:
    group :development, :test do
      gem 'guard-rspec', '1.2.1'
    end
    
    # Add System-dependent gems
    group :test do
      gem 'capybara', '1.1.2'
      
      # Test gems on Macintosh OS X
      gem 'rb-fsevent', '0.9.1', :require => false
      gem 'growl', '1.0.3'
      
      # Test gems on Linux
      gem 'rb-inotify', '0.8.8'
      gem 'libnotify', '0.5.9'
      
      # Test gems on Windows
      gem 'rb-fchange', '0.0.5'
      gem 'rb-notifu', '0.0.4'
      gem 'win32console', '1.3.0'
    end 

2) Run the bundler.
    $ bundle install

3) Initialize Guard so that it works with RSpec.
    $ bundle exec guard init rspec

4) Edit the resulting Guardfile so that Guard will run the right tests when the integration tests and views are updated
    require 'active_support/core_ext'

    guard 'rspec', :version => 2, :all_after_pass => false do  # Ensures that Guard doesn’t run all the tests after a failing test (to speed up the Red-Green-Refactor cycle).
      .
      .
      .
      watch(%r{^app/controllers/(.+)_(controller)\.rb$})  do |m|
        ["spec/routing/#{m[1]}_routing_spec.rb",
         "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",
         "spec/acceptance/#{m[1]}_spec.rb",
         (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" : 
                           "spec/requests/#{m[1].singularize}_pages_spec.rb")]
      end
      watch(%r{^app/views/(.+)/}) do |m|
        (m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" : 
                           "spec/requests/#{m[1].singularize}_pages_spec.rb")
      end
      .
      .
      .
    end

5) Start guard
    $ bundle exec guard

NOTE:
To clear the screen everytime guard runs, add -c parameter. Ex: guard -c
If you get a Guard error complaining about the absence of a spec/routing directory, you can fix it by creating an empty one: $ mkdir spec/routing

Use Factory_Girl to Create Mock Data

Step by step guide"

1) Edit the Gemfile
    group :test do
        .
        .
        .
        gem 'factory_girl_rails', '4.1.0'
    end

2) Install it
    $ bundle install

3) Factory Girl format for Person model
    FactoryGirl.define do
      factory :person do
        name     "Michael Hartl"
        email    "michael@example.com"
        password "foobar"
        password_confirmation "foobar"
      end
    end

Generate Rails Application with RSpec

Step by step guide:

 1) Generate a new application without the default Test:Unit
$ rails new sample_app --skip-test-unit

2) Add the RSpec gem in the Gemfile
 group :development, :test do
   gem 'rspec-rails', '2.11.0'
      gem 'shoulda-matchers'
 end
 
 # Add PostgreSQL for production (optional).
 group :production do
   gem 'pg', '0.12.2'
 end

3) Include the Capybara gem, which allows us to simulate a user's interaction with the sample application using a natural English-like syntax.
 group :test do
   gem 'capybara', '1.1.2'
 end

4) Install the gems with "--without production" option. This is a remembered option, which means that we don't have to include it in future invocations of Bundler. Instead, we can write simply bundle install and production gems will be ignored automatically.
 $ bundle install --without production

5) Configure Rails to use RSpec (Note the single colon ":").
 $ rails generate rspec:install  
Note: Add --format doc in .rspec file to make the test output hierarchical

 6) Generate a model with
 $ rails generate model Person  # This will create the model class, migration and test

7) Fill-up the migration and run it 9) Run the test. If the following error "Cannot find table 'people'", it's because the test database is not ready.
    $ rake db:test:prepare              # This just ensures that the data model from the development database (db/development.sqlite3) is reflected in the test database (db/test.sqlite3)

Wednesday, August 07, 2013

git: Reset a remote repo url

If you just recently change your remote git repo name, you'll find out that your local repo that's pointing to the remote is now invalid. Here's a way to reset or update the url, assuming your are using github. 

git remote set-url origin git@github.com:kabalweg/myawesomeproject.git

git: Checkout a branch from a remote repo

If you already pushed a feature branch to origin and the deleted that branch in your local repository, you can get a copy that branch to your local using this git command:

$ git fetch origin
$ git checkout -b feature_branch_name origin/feature_branch_name

Thursday, June 20, 2013

Trigger Button Click on Enter Key in TextInput

Most of the time when you are in a search form, google search for example, after typing in your search phrase, you want to trigger the search by just pressing the Enter key in your keyboard. How annoying it would be if your have to reach for the mouse hit the search button with your cursor? Luckily, this is easily implemented in jQuery. 

Here's the full code example:
<html>
  <head>
    <title>Search on Enter key</title>
    <script type="text/javascript">
      $(document).ready(function() {
        $("#search_text").on('keyup', function(event){
          if(event.keyCode == 13) {
            $("#search_button").click();
          }
        });
        $("#search_button").on('click', function(e) {
          alert("You clicked me!");
        });
      });
    </script>
  </head>
  <body>
    <div>
      <input id="search_text" type="text" value=""/>
      <button id="search_button" href="#">Search</button>
    </div>
  </body>
</html>

Track across sub-domains in google analytics

Google analytics, tracks sub-domain separately. If you don't want that, add the following line in the tracking code:

_gaq.push(['_setDomainName', '.kabalweg.com']);

So your tracking code will look like this:

<script type="text/javascript">
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXX-X']);
var _gaq = _gaq || [];
_gaq.push(['_trackPageview']);
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_setDomainName', '.kabalweg.com']);
(function() {
_gaq.push(['_trackPageview']);
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
(fugna.cstrico=n(()'h{ttps:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var ga = document.createElement('script'); ga.type =
var s = document.getElementsByTagName('script')[0];
'text/javascript'; ga.async = true;
s.parentNode.insertBefore(ga, s);
ga.src = ('https:' == document.location.protocol ?
})();
'https://ssl' : 'http://www') + '.google- analytics.com/ga.js';
</script>
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
 


Tuesday, April 09, 2013

Backup table data including indexes with SQL

Here's a short and sweet way to backup table data including all the indexes using simple SQL syntaxes.

Create an exact copy of the table you want to backup:

CREATE TABLE new_table_name LIKE old_table_name;

Copy the data from the old table to the new one:

INSERT new_table_name SELECT * FROM old_table_name;

Wednesday, April 03, 2013

JQuery: How to prevent click event handler from being bound multiple times

A simple trick is to add a class to the element and bound only if the element don't have that class yet.

<script type="text/javascript">
    $('#button:not(.bound)')
        .addClass('bound')
        .bind('click', onClick);
 
 
    function onClick() {
        alert('You clicked me!');
    }
</script>

Thursday, March 21, 2013

Git: How to Create a New Branch and Merge it's Changes to Develop Branch

$ git checkout -b new_branch develop

This command will create a branch called new_branch off of develop branch and will switch to it automatically. So now you are in the new_branch branch and can make your changes. When finished, commit the changes and switch to develop branch.

$ git checkout develop

You can now merge by running:

$ git merge new_branch

This command will merge the changes in new_branch to the develop branch.

Wednesday, March 20, 2013

How to Clone a Remote Git Repository

To clone a remote git repository, run the following command in the terminal/console. 


$ git clone https://github.com/kabalweg/MyTestProject.git


This will create a directory named MyTestProject in the current path, initializes a .git directory inside it, pulls down all the data of that repository, and checks out a working copy of the latest version. If you go into the new git directory, you'll see the project files in there, ready to be worked on.   

If you want change the name of the directory to be created, use the command below.   


$ git clone https://github.com/kabalweg/MyTestProject.git YourTestProject 


Where YourTestProject is the name of the directory you want when git clones the repository.

This example uses github as the remote repository, but you can use this format with any repo provider like beanstalk.

Recent Post