Why I Do Combining Apache and Nginx Together?

Why I do combining apache and nginx together?

Nginx and apache are powerful and effective servers by nowadays. Apache currently reigns as the number 1 server for websites and since its public release in 2006. And nginx has taken the world by storm and is now the number 2 server for active sites.

The Reason Why I Use Nginx and Apache Together is

Nginx
- nginx serves static files (images, css, html etc.) really fast and efficient and passes php and .htaccess requests to apache for processing.
- nginx needs the help of php-fpm or similar modules for dynamic content.

Apache
- apache is hard on server memory.
- apache serves php and .htaccess (most cms site like wordpress needs it for rewrite) and if you throw in a php opcode cache like zend opcache or xcache it should serve php even faster.

nginx + apache with php opcache = performance and server resource efficiency

So far so good, in the next article I will show you the configurations. That’s it!!! See ya!!! :)

Create Content With Multiple Features With CKEditor Gem

Create content with multiple features with CKEditor Gem

Setup & Usage
First, we need to add the CKEditor gem to our Gemfile. Open up your Gemfile and add the line listed below:

Gemfile
1
gem "ckeditor"

Next, open up the terminal and run a bundle install to install the gem:

1
bundle install

Great, now lets create a sample model and accompanying controller that will be used to store our data. Open up and run the command below to create the Magazine model and migrate the database:

1
2
rails g resource Magazine title body:text
rake db:migrate

Now, open your routes file and add the following line to your routes:

routes.rb
1
root to: "magazines#index"

Now, lets add the CKEditor javascript include to our application.js. Modify your application.js file so that it looks like the code listed below:

application.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require ckeditor/init
//= require turbolinks
//= require_tree .

Great, now we need to add some code to the magazines controller. Add the following code to the magazines controller:

magazines_controller.rb
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
class MagazinesController < ApplicationController
  def index
    @magazines = Magazine.order("created_at DESC")
  end

  def show
    @magazine = Magazine.find(params[:id])
  end

  def new
    @magazine = Magazine.new
  end

  def create
    @magazine = Magazine.new(magazine_params)
    if @magazine.save
      redirect_to magazines_path, notice: "The magazines has been successfully created."
    else
      render action: "new"
    end
  end

  def edit
    @magazine = Magazine.find(params[:id])
  end

  def update
    @magazine = Magazine.find(params[:id])
    if @magazine.update_attributes(magazine_params)
      redirect_to magazines_path, notice: "The magazine has been successfully updated."
    else
      render action: "edit"
    end
  end

  private
  def magazine_params
    params.require(:magazine).permit(:title, :body)
  end
end

This code enables the ability to read, write, and update the magazines in our example. Now for the views, first lets create the index view:

index.html.erb
1
2
3
4
5
6
7
8
9
<%= link_to "New Magazine", new_magazine_path %>
<% @magazines.each do |magazine| %>
  <h3><%= magazine.title.html_safe %></h3>
  <p><%= magazine.body.html_safe %></p>
  <%= link_to "Edit Magazine", edit_magazine_path(magazine) %>
  <% if magazine != @magazines.last %>
  <hr />
  <% end %>
<% end %>

Now, lets create a partial to store the form. Create a file called app/views/_form.html.erb and add the code listed below:

_form.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<% if @magazine.errors.any? %>
  <ul>
    <%= @magazine.errors.full_messages.each do |message| %>
        <li><%= message %></li>
    <% end %>
  </ul>
<% end %>
<%= form_for @magazine do |f| %>
  <div>
    <%= f.label :title %>
  </div>
  <div>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.label :body %>
  </div>
  <div>
    <%= f.cktext_area :body, rows: 10 %>
  </div>
  <div>
    <%= f.submit %>
  </div>
<% end %>

Now, lets create the new view. Create the app/views/magazines/new.html.erb file and add the code listed below:

new.html.erb
1
2
<h3> New Magazine</h3>
<%= render "form" %>

Now, if you visit the new magazines page on your development server you will see that CKEditor appears.

Next lets create the edit view. Create the app/views/magazines/edit.html.erb file and add the code listed below:

edit.html.erb
1
2
<%= "Editing #{@magazine.title}" %>
<%= render "form" %>

Great, now when you click ‘edit magazine’ on any magazine, it will show the CKEditor for editing.

Images Using Paperclip
In order to integrate images via paperclip, a few more steps are required. Note that you must have ImageMagick installed for this to work. First, lets include the paperclip gem:

Gemfile
1
gem "paperclip"

Next, we need to run a generator provided by ckeditor. This generator will create the necessary models that will be used to store image data. Run the command below:

1
2
rails generate ckeditor:install --orm=active_record --backend=paperclip
rake db:migrate

So far so good, if you restart your rails server and refresh the page, you will be able to click the images button, upload an image, and insert it into your articles.

Gulp – Markdown

Gulp, Gulp – Markdown

Now for someting new. We are going to use Gulp with Handlebars to create our own CMS system.

First of all, We want to be able to process markdown files and create html files with Gulp with plugin.

1
$ npm install gulp-markdown --save-dev

For more information about gulp-markdown check out https://www.npmjs.org/package/gulp-markdown

We will read all the markdown files in the contents/pages folder and generate html files.

gulpfile.js
1
2
3
4
5
6
7
8
...
var markdown = require('gulp-markdown');
...
gulp.task('generate_pages', function() {
  return gulp.src('content/pages/**.md')
    .pipe(markdown())
    .pipe(gulp.dest("build/pages"));
});

Lets create our first page.

ontents/pages/first_page.md
1
Yes, it makes a **bold** statement.

When We run our gulp generate_pages task, We will take the markdown and convert it into html and place the files in the build/pages directory.

1
2
3
4
$ gulp generate_pages
Using gulpfile ~/js/gulpwalkthru/gulpfile.js
Starting 'generate_pages'...
Finished 'generate_pages' after 22 ms

If We look in our build/pages directory, We should see our new html file.

build/pages/first_page.html
1
p>Yes, it makes a <strong>bold</strong> statement.</p>

If We visit http://localhost:8000/pages/first_page.html we should see our generated webpage.

Gulp – Live Reload

Gulp, Gulp – Live Reload

So far so good, lets link our css file in index.html.

/contents/index.html
1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
  <head>
    <title>Learning Gulp</title>
    <link rel="stylesheet" href="/styles/main.min.css" />
  </head>
  <body>
    <h1>Hello Gulp!</h1>
  </body>
</html>

Now let’s turn on live reload with our gulp-webserver.

gulpefile.js
1
2
3
4
gulp.task('webserver', function() {
  return gulp.src('build')
    .pipe(webserver({ livereload: true }));
});

If we run gulp webserver in one terminator and gulp watch in another, we will have our webserver running and live refreshing on each build.

terminator1:

1
$ gulp webserver

terminator2:

1
$ gulp watch

Update the css file to:

/contents/styles/some_styles.css
1
2
3
h1 {
  color: blue;
}

Go to http://localhost:8000 to watch our webpage.

Gulp – Web Server

Gulp, Gulp – Web Server

We can actually serve our webpages by using a gulp plugin.

1
$ npm install gulp-webserver --save-dev

For more information about gulp-webserver check out https://www.npmjs.com/package/gulp-webserver

gulpfile.js
1
2
3
4
5
6
7
...
var webserver = require('gulp-webserver');
...
gulp.task('webserver', function() {
  return gulp.src('build')
    .pipe(webserver());
});

Now when we run our gulp task webserver we will have a local webserver to view our website.

1
2
3
4
5
6
$ gulp webserver

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'webserver'...
Webserver started at http://localhost:8000
Finished 'webserver' after 20 ms

If you go to http://localhost:8000 in your web browser you should see our index.html page saying Hello Gulp!.

Gulp – Watch

Gulp, Gulp – Watch

Now for something super amazing. Instead of running the gulp task explicitly, lets have gulp run our tasks when the files change.

First reorganize some of our tasks:
- Rename default task to css.
- Create a new default task to run css, ‘javascript’, and ‘homepage’ tasks.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
...
gulp.task('css', ['clean'], function() {
  console.log("Concat, move, and minify all the css files in styles folder");
  return gulp.src("contents/styles/**.css")
    .pipe(concat('main.min.css'))
    .pipe(cssmin())
    .pipe(gulp.dest('build/styles'));
});
...
gulp.task('default', ['css', 'homepage', 'javascript']);
...

Next create our file watching task. Could you guess what?… there isn’t a plugin for this. It is just part of gulp.

We will create a gulp watch task to watch our contents folder and run our default task on file change.

gulpfile.js
1
2
3
4
5
...
gulp.task('watch', [], function() {
  return gulp.watch(['contents/**'], ['default']);
});
...

In the terminal type:

1
2
3
4
5
$ gulp watch

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'watch'...
Finished 'watch' after 11 ms

If you update any of the css files in the styles folder, you should see gulp run the default task.

1
2
3
4
5
6
7
8
9
10
11
12
13
Starting 'clean'...
Clean all files in build folder
Finished 'clean' after 21 ms
Starting 'css'...
Concat, move, and minify all the css files in styles folder
Starting 'homepage'...
Starting 'javascript'...
Validate, Concat, Uglify, and Move all the javascript files
Finished 'homepage' after 77 ms
Finished 'javascript' after 75 ms
Finished 'css' after 84 ms
Starting 'default'...
Finished 'default' after 14 μs

Gulp – Creating a Webpage

Gulp, Gulp – Creating a Webpage

Moving CSS and JavaScript files is all well and good, but we do actually want webpages right?

Let’s start our webpage generation by first moving the index.html file we created while learning more about streams.

It should look like:

/contents/index.html
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
  <head>
    <title>Learning Gulp</title>
  </head>
  <body>
    <h1>Hello Gulp!</h1>
  </body>
</html>

We will then create a simple homepage task to move the index.html file to our build directory.

gulpfile.js
1
2
3
4
5
...
gulp.task("homepage", function() {
  return gulp.src("contents/index.html")
    .pipe(gulp.dest("build"));
});

Now test the task.

gulpfile.js
1
2
3
4
5
$ gulp homepage

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'homepage'...
Finished 'homepage' after 15 ms

It would be nice to be able to preview our website as we generate the content. Let’s do that next.

Gulp – Testing With Jasmine

Gulp, Gulp – Testing with Jasmine

You do test your JavaScript right? Well… you should and with gulp + Karma + Jasmine it is super easy.

First if you have not installed Karma and Jasmine, then do so now.

1
$ npm install karma-jasmine --save-dev

Next we will install the gulp-jasmine plugin for gulp.

1
$ npm install gulp-jasmine --save-dev

We can then create a test task to run all the specs found in a specs folder we will create.

gulpfile.js
1
2
3
4
5
6
var jasmine = require('gulp-jasmine');
...
gulp.task('specs', function () {
  return gulp.src('specs/**.js')
    .pipe(jasmine());
});

Let’s create a basic (failing) test to see that it is working.

/specs/our_test.js
1
2
3
4
5
describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(false);
  });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ gulp specs

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'specs'...
F

Failures:

  1) OMG a JavaScript Test should pass
  1.1) Expected true to be false.

1 spec, 1 failure
Finished in 0.004 seconds
'specs' errored after 39 ms Tests failed

Now it is time to refactor. We will make the extremely difficult change from false to true to make our test pass.

/specs/our_test.js
1
2
3
4
5
describe('OMG a JavaScript Test', function() {
  it('should pass', function() {
    expect(true).toBe(true);
  });
});

And run our test suite again.

1
2
3
4
5
6
7
8
9
$ gulp specs

Using gulpfile ~/YOUR_DIRECTORY/gulpfile.js
Starting 'specs'...
.

1 spec, 0 failures
Finished in 0 seconds
Finished 'specs' after 39 ms

Next we will do is improve our testing task by adding a test-watch task to run as we edit our JavaScript files.

gulpfile.js
1
2
3
4
...
gulp.task('spec-watch', function() {
  gulp.watch(['specs/**.js', 'contents/javascripts/**.js'], ['test'])
});

Gulp – Uglify

Gulp, Gulp – Uglify

For JavaScript files we also want to uglify them. Uglifying JavaScript involves changing variable and function names to reduce their size. So a variable named customer might be renamed to x. JavaScript engines don’t care about descriptive names, only developers. So how do we uglify JavaScript files with gulp?

I know what you are going to say: “Blah, blah, blah… there is a plugin.” and you are correct.

1
$ npm install gulp-uglify --save-dev

For more information on gulp-uglify check out https://www.npmjs.org/package/gulp-uglify.

While we are uglifying the file, we will also concat all our JavaScript files together and move them to build/javascripts.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
...
var uglify = require('gulp-uglify');
...

gulp.task('javascript', function () {
  console.log("Validate, Concat, Uglify, and Move all the javascript files");

  return gulp.src("contents/javascripts/**.js")
    .pipe(jsValidate())
    .on("error", notify.onError(function(error) {
      return error.message;
    }))
    .pipe(uglify())
    .pipe(concat('main.js'))
    .pipe(gulp.dest('build/javascripts'));
});

When you run our gulp javascript task now, we should see that our javascript files were uglified, concated, and moved to the build folder.

1
2
3
4
5
6
$ gulp javascript

Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'javascript'...
Validate, Concat, Uglify, and Move all the javascript files
Finished 'javascript' after 55 ms

If you have an error here, be sure to check that your JavaScript is valid. Remember we were testing that last section.

The build script should create our /build/javascripts/main.js file.

/build/javascripts/main.js
1
function OMG(){var n=2;return n+10}

Gulp – Notify Pop Up

Gulp, Gulp – Notify Pop Up

In the previous article, we used gulp to validate our JavaScript. The error message would appear in the console. While this is awesome, there is a chance we could miss it.

Let’s use notifications to display a pop up window when we have a JavaScript error.

There is a gulp plugin to send notifications.

1
$ npm install gulp-notify --save-dev

For more information on gulp-notify check out https://www.npmjs.org/package/gulp-notify

Remember that gulp uses node’s streaming. It shouldn’t be a surprise that when gulp-jsvalidate finds an error, it emits an error event.

All we need to do is handle the event and use gulp-notify to send a notification with the error message.

gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
var notify = require('gulp-notify');
...

...
gulp.task('javascript', function () {
  console.log("Validate JavaScript");
  return gulp.src("contents/javascripts/**.js")
    .pipe(jsValidate())
    .on("error", notify.onError(function(error) {
      return error.message;
    }));
});
...

Since our JavaScript is now valid, we need to make it invalid so we can see the error message.

/contests/javascript/somejs.js
1
2
3
4
function OMG() {
  var x * 2;
  return x + 10;
}

Now when we run gulp javascript we will get a notification window that an error was found.

1
2
3
4
5
6
7
$ gulp javascript

Using gulpfile ~/YOUR_DIRECTORY/gulpFile.js
Starting 'javascript'...
Validate JavaScript
gulp-notify: [Error running Gulp] Line 3: Unexpected token *
'javascript' errored after 41 ms Line 3: Unexpected token *