Holiday alert module for PrestaShop

Last year I got a client that needed me to help them with the technical part of the e-commerce PrestaShop. Although I didn’t use PHP for over a year I accepted the challenge and for Christmas they wanted to show an alert to their clients because the orders wouldn’t be processed till January.

This was a good chance to dig into the process of creating a PrestaShop module and I implemented a simple module that shows a message in the top of the e-shop or in the shopping cart page.

For the layout of the box I’m using the one of Bootstrap so you can choose among four colours. This can be configured in the back-end as well as the message of the alert.

Today I have created a GitHub repository where I’m sharing the code of this module and hopefully soon there will be others.

Let me know how it goes if you use it!

Tagged , , ,

Using Grunt to run Mocha tests with Backbone.js and RequireJS

I don’t have all the time that I would like for writing here but before the end of the year it’s time for a new blog post.

This year has been really prolific for me learning new things with JavaScript and in the last months I have adopted the Yeoman workflow, which really helps to develop web applications.

One of the tools included in Yeoman is Grunt, a task runner that is used to build, preview and test the project.

In the process of converting a Backbone.js + RequireJS app to this Yeoman workflow, I had a hard time figuring the right configuration to run tests both in the command line and the browser. There are several blog posts and repositories talking about it but non of them worked for me so I’m summarizing my experience here.

I’m assuming you have created an application using Yeoman as follows:

mkdir app
cd app
yo backbone

So the mocha task in the Gruntfile.js is the default one but the run parameter has to be set up to false. You can change the mocha reporter as you like and add as well options for logging so you can track any error.

        mocha: {
            all: {
                options: {
                    log: true,
                    reporter: 'Spec',
                    run: false,
                    timeout: 10000,
                    urls: ['http://localhost:<%= connect.test.options.port %>/index.html']
                }
            }
        },

I added Mocha and Chai as developer dependencies so they can be downloaded with the package manager Bower, which is another Yeoman tool. After this you can remove the lib folder inside of the test folder.

{
  "name": "backbone-app",
  "version": "1.0.0",
  "dependencies": {
    "jquery": "~1.9.0",
    "underscore": "~1.4.3",
    "backbone": "~1.0.0",
    "requirejs": "~2.1.5",
    "requirejs-text": "~2.0.5"
  },
  "devDependencies": {
      "mocha": "*",
      "chai": "*"
  }
}

Another key point was including the test framework and the assertion library inside of script tags in the HTML code and not trying to load them using RequireJS.

<!doctype html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Mocha Spec Runner</title>
    <link rel="stylesheet" href="bower_components/mocha/mocha.css">
</head>
<body>
    <div id="mocha"></div>

    <script src="bower_components/mocha/mocha.js"></script>
    <script>mocha.setup('bdd')</script>
    <script src="bower_components/chai/chai.js"></script>
    <script>var expect = chai.expect</script>

    <script data-main="spec/runner" src="bower_components/requirejs/require.js"></script>
</body>
</html>

Then I created a spec runner which is the main entry point for RequireJS to load the test files and its configuration.

'use strict';
require.config({
    baseUrl: 'scripts/',
    paths: {
        jquery: '../bower_components/jquery/jquery',
        backbone: '../bower_components/backbone/backbone',
        underscore: '../bower_components/underscore/underscore'
    },
    shim: {
        underscore: {
            exports: '_'
        },
        jquery: {
            exports: '$'
        },
        backbone: {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        }
    }
});

var specs = [
    'spec/collections.examples.js',
    'spec/models.example.js'
];

require(specs, function() {
    mocha.run();
});

Now you can create a test file for a Backbone collection like this:

/*global define, describe, it, expect */
'use strict';
define(function(require) {
    var ExamplesCollection = require('collections/examples');

    describe('Examples collection', function() {

        var examples = new ExamplesCollection();

        it('should exist', function() {
            expect(examples).to.exist;
        });

        it('should be an instance of Examples collection', function() {
            expect(examples).to.be.an.instanceof(ExamplesCollection);
        });

    });

});

To run the tests through the command line you just need to run grunt test. If you want to run them in the browser load http://localhost:9001/index.html after typing grunt server:test.

Don’t forget as well to run bower install to download the dependencies and check that the app folder is being mounted for the test task.

            test: {
                options: {
                    port: 9001,
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, 'test'),
                            mountFolder(connect, yeomanConfig.app)
                        ];
                    }
                }
            },

Merry Christmas and Happy Coding!

Tagged , , , , ,

Testing email sending in Django

During the past three months I have developed my first two websites in Python using the Django framework.

Following the tutorial was a great start and it didn’t take me that long to get adapted to Python coming from a PHP background. But when you want to go further the documentation is rather vague and confusing in my opinion.

This week I got to the point where I wanted to test the email functionality. Django offers quite a nice tool while you are developing a website; if you want to see the output of your emails, you can just write them to a file adding a couple of settings.

EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = os.path.join(PROJECT_ROOT, 'tmp')

In addition to this I wanted to check the email configuration before going production, but already using the final parameters for the required settings:

EMAIL_HOST=''
EMAIL_HOST_PASSWORD=''
EMAIL_HOST_USER=''
EMAIL_PORT = 25
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = ''
SERVER_EMAIL = ''

The problem is that when Django sets up the testing environment, it changes the email backend to the one in-memory. Fortunately, this behavior can be overridden so you can run a test case with the following code to check if your mail is being actually sent.

 
from django.test import TestCase
from django.core import mail
from django.test.utils import override_settings

@override_settings(EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend')
class EmailTest(TestCase):       
    def test_send_email(self):
        mail_sent_success = mail.send_mail('Subject here', 
                       'Here is the message.',
                       '', ['pablo@esebesoftware.com'],
                       fail_silently=False)
        self.assertEquals(mail_sent_success, 1)

Notice that DEFAULT_FROM_EMAIL is used if omitting the from_email field.

Tagged , , ,

Backbone.js internationalization with Polyglot.js by airbnb

In the past few weeks I have been digging deeper into Backbone.js, a really cool JavaScript library that gives structure to any web application providing models, collections and views in the client-side. If you want to know more, there are at least a couple of good links out there you should check out: one is the free book Developing Backbone.js Applications by Addy Osmani; the other is the series of posts by Christophe Coenraets in his blog, where you can see real code in action. For modularizing the app I have followed this tutorial using RequireJS.

While developing the app I came to a common issue which is internationalization (i18n), as it was required to support at least two different languages: English and German. And as I didn’t have any previous experience with this on Backbone.js, I decided to choose a modern library like Polyglot.js released two months ago by the guys at Airbnb (you can read more about their experience implementing the new mobile web using Node.js).

It took me a while to figure out how to use Polyglot, but the first thing it’s to properly configure Require to export the Polyglot object:

require.config({
  paths: {
    jquery: 'libs/jquery',
    underscore: 'libs/underscore',
    backbone: 'libs/backbone',
    text: 'libs/require/text',
    polyglot: 'libs/polyglot',
    templates: '../templates',
  },
  shim: {
    underscore: {
      exports: '_'
    },
    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    },
    polyglot: {
      exports: 'Polyglot'
    },
  }
});

For using Polyglot, we have to instantiate the object and give it a phrases objects with pairs key/value corresponding to the language of the user’s locale. By the nature of our application I have decided to store this locale in the client using the HTML5 local storage capabilities. For the language files I’m using pure JSON objects containing the pairs and storing them into a locales folder.

{
  'page': 'Page',
  'time': 'Time'
}
{
  'page': 'Seite',
  'time': 'Zeit'
}

To retrieve the corresponding language file upon initialization of the app,  I’m requesting the file through a regular getJSON call with JQuery. Is not a real Backbone-ish way, but I feel that creating a Model could be overkilled.  Anyway, as I said, I’m just starting with Backbone so I’m open to any suggestion or recommendation.

define([
'jquery',
'underscore',
'backbone',
'polyglot',
'router', // Request router.js
], function($, _, Backbone, Polyglot, Router) {

var initialize = function() {
  var locale = localStorage.getItem('locale') || 'de';
  // Gets the language file.
  $.getJSON('locales/' + locale + '.json', function(data) {
    // Instantiates polyglot with phrases.
    window.polyglot = new Polyglot({phrases: data});
    // Pass in our Router module and call it's initialize function
    Router.initialize();
  });
}
return {
  initialize: initialize
};

});

After instantiating Polyglot with the phrases retrieved from the JSON file, I assign it to the window object, so we can use polyglot.t() to get the translations in our HTML templates as follows:

<div><%= polyglot.t('time') %></div>
Tagged , , , , ,

Centered heading overlaying a horizontal line with CSS

After the introductory post I’m going to start writing about CSS, even when it’s not my favourite language as I’m always feeling I spend way too much time for things that should be simpler.

Four weeks ago, while I was implementing a CSS design, I faced the problem of centering the heading overlaying a horizontal line and I found this great post by Louis Lazaris.

Unfortunately, none of the solutions there were valid for me as I needed also to have transparent background. So I started to play with the pseudo-elements till I got the solution.

Giving height and background-color to the pseudo elements :before and :after, together with negative margins of the same size than the heading, defined as 50 %, makes the trick, that I think it’s easy to understand seeing it in action on a fiddle.

Besides allowing any kind of background, my solution doesn’t add any extra HTML tag and scales with every size of text.

h1 {
 overflow: hidden;
 text-align: center;
}
h1:before,
h1:after {
 background-color: #000;
 content: "";
 display: inline-block;
 height: 1px;
 position: relative;
 vertical-align: middle;
 width: 50%;
}
h1:before {
 right: 0.5em;
 margin-left: -50%;
}
h1:after {
 left: 0.5em;
 margin-right: -50%;
}
Tagged , ,
Follow

Get every new post delivered to your Inbox.

Join 1,036 other followers