Extending Class methods with Module Mixins

I’m about to finish the Eloquent Ruby book (excellent book by the way) and keep finding ruby pearls of wisdom. One of these is that you can actually use module mixins to extend class methods! You only need to declare a module mixin as normal, and then include it on the singleton class of your declared class (“Klass” in our example).

Then we can use it just like any other class method.

Ruby tips

I just read the Ruby Pocket Reference, a great intro for the Ruby language and want to share a few helpful Ruby tips learned.

Parallel assignment of variables

In Ruby, you can assign several values to several variables in a single expression (aka. one-liner). The values can be of any type, making it even better! The result is pretty impressive, check out the snippet below :

You can even return multiple values from methods!

And in case the above example didn’t quite impress you, see how convenient it can be on a real-world example :

Here Documents

You can build multiple line strings using here documents. Ruby supports both single and double-quoted strings on here documents, have a look at the examples :


Ruby supports ranges of numbers which can be very handy. You can define a range of numbers using the starting value followed by .. (2 dots) or ... (3 dots) and the end value. On the first case the range includes the last value, and on the other one excludes it. For example :

Ranges can be used in many cases such as :



and creating arrays

Default arguments

Another great feature!

block_given? on yields

A yield statement executes a code block associated with a method. You probably know that already (if not have a look at the examples below), what you probably don’t know is the block_given? method that checks if a code block is passed to the method.

Case statement tricks

Case staments in Ruby are very flexible. They come in two main flavors, multiline for writing many statements and one-liners, that looks much better:

You can also assign a value using the case statement in Ruby:

Usefull object instance methods

As a final tip, I enlist the most useful public methods of the Object class (the base class for Ruby, all other types inherit these methods). All of them are helpful, but I tend to use the debugging-oriented ones the most :

  • obj.inspect
  • obj.class
  • obj.ancestors
  • obj.instance_variables
  • obj.methods (also obj.private_methods, obj.protected_methods and obj.public_methods can be handy as well)
  • obj.to_s (sometimes obj.to_a can be handy as well)

Not bad for an introductory Ruby book. If you like the post stay tuned for more!

Avoid CoffeeScript & use ES6!

Those of you that follow my blog might have noticed how fond I am to some of CoffeeScript’s conveniences. They are excellent, but it’s time to leave them behind and start using ES6. Most of CoffeeScript’s goodies already exist in ES6 (with some syntax changes), and your code is guaranteed to be future proof. And if time spent learning CoffeeScript feels like a waste, there’s good news – with a solid CoffeeScript base, transitioning to ES6 will be a piece of cake!

Coffeescript gotchas (part 4): Scope and Objects

This is the fourth and final part of the CoffeeScript gotchas series. On this part I’ll demonstrate Coffeescript’s syntactic sugar on Objects, constructors and classes! Ready, set, go…

Update: Table of contents


Probably the most valuable feature that CoffeeScript syntax offers at the moment. With the class keyword you can create a new class (CoffeeScript is using the constructor function under the hood) and with the extend keyword you can extend one. To make things even easier, CoffeeScript provides an initialization (aka constructor) function, in case you need it. Just use the contstructor method and you are ready to go. You can use the concept of super method which represents a reference to the superclass version of the method you’re in (very Ruby-like). I’m sure that all these will make more sense with the following example…

class Animal
  constructor: (@name) ->
  move: (meters) ->
    console.log "#{@name} moved #{meters} meters."

class Snake extends Animal
  move: ->
    console.log "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    console.log "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"


See the Pen Coffeescript gotchas (part 4): Classes by John Tsevdos (@tsevdos) on CodePen.


You can set up instance variables with the classic this Javascript keyword (CoffeeScript translates to Javascript after all), but you can save a couple of characters and maybe lines, by using the @ symbol. You can also save a couple of more lines by omitting the instance name.

class Animal
  constructor: (name, height, weight) ->
    @name = name
    @height = height
    @weight = weight

# same as above
class Animal
  constructor: (@name, @height, @weight) ->

See the Pen Coffeescript gotchas (part 4): Constructors by John Tsevdos (@tsevdos) on CodePen.


Finally, if you want to pass an instance method as a callback, use the =>, also known as “fat arrow”. The “fat arrow” binds the object’s instance to this and makes your code easier to read. This will also be an ES6 feature, so it makes a lot of sense to get used to it.

class Message
  constructor: (@txt) ->
  thin: -> console.log @txt
  fat:  => console.log @txt

msg = new Message "yo"
msg.thin() # works
msg.fat()  # works

fn = (callback) -> callback()

fn(msg.thin) # => "undefined"
fn(msg.fat)  # works
fn(-> msg.thin()) # works

See the Pen Coffeescript gotchas (part 4): Scope by John Tsevdos (@tsevdos) on CodePen.

This has been the final part of the series – see you around and stay tuned.

Coffeescript gotchas (part 3): Switch statement and loops

Welcome to the third part of Coffeescript gotchas. If you haven’t yet read the first and second part of the series I strongly recommend to have a look. The main topic today is loops plus the switch statement. CoffeeScript offers a lot of enchantments and syntactic sugar to them.

Update: Table of contents

Switch statement

At last, an easier way to write switch statements. If your switch case contains a single line of code, you can write the entire thing in a single line using the then keyword (see second example).

name = "John"

# normal switch statement
switch name
  when "John"
    console.log "This guy rocks!"
  when "Jon"
    console.log "Still cool guy"
    console.log "Good lad."
# switch statement using the then keyword
switch name
  when "John" then console.log "This guy rocks!"
  when "Jon" then console.log "Still cool guy"
  else console.log "Good lad."

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

For Loops

For loops have many flavors and great potential in CoffeeScript. You can loop through arrays and objects and still keep your code clean and hassle-free. Just take a deep breath and try to absorb as many flavours as you can. They can all come very handy.


Iterating Arrays have never been easier…

arr = ["Ned Stark", "Jon Snow", "Arya Stark", "Jaime Lannister"]

# basic array iteration
for name in arr
    console.log name

# array iteration (with index)
for name , i in arr
    console.log "#{i}: #{name}"

# array filtering (with index)
for name, i in arr when name.indexOf "J" is 0
    console.log "#{i}: #{name}"

# array iteration for every second item
for name , i in arr by 2
    console.log "#{i}: #{name}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.


Looping through an object’s key/value pairs is also very easy. You can also loop through just the direct key/value pairs (not the inherited ones) by using the own keyword (which will use the hasOwnProperty method under the hood).

ned =
  name : "Ned Stark"
  house : "Stark"
  words : "Winter is coming"

# print all properties of an object
for key, value of ned 
  console.log "#{key} : #{value}"

# print all own properties of an object
for own key, value of ned
  console.log "#{key} : #{value}"

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

While Loops

The while loop has 3 syntax flavors to make your code more descriptive and your life easier. Try to use unless instead of while not, as it’s easier and preferable.

# Normal while
num = 10
while num
  console.log num

# while not
num = 10
while not (num is 0)
  console.log num

# exactly the same as the above example
num = 10
until num is 0
  console.log num

See the Pen Coffeescript gotchas (part 3): switch statement and loops by John Tsevdos (@tsevdos) on CodePen.

As you can see CoffeeScript is very handy when it comes to loops. Keep in mind and stay tuned for the fourth and final part of the Coffeescript gotchas series where we’ll have a look at the syntactic sugar that CoffeeScript provides on Scope and Objects.

Coffeescript gotchas (part 2): Operators and aliases

For this second part of the series, we’ll dig into CoffeeScript operators and their aliases, which make our lives easier and our code much cleaner and more expressive. In case you missed the first part I recommend you have a look at it, I’m sure you’ll find something interesting.

Update: Table of contents

Basic operators and their aliases

When it comes to if statements (and not only them), CoffeeScript provides many syntax aliases that keep our code clean and readable. For starters, we can forget triple equals (===) and negative double equals (!==), and use their easier aliases, the is and isnt keywords. Have a look at the example below.

name = "John"

if name is "John" # true ( is equals === )
  console.log('is demonstration')
if name isnt "Johnny" # false ( isnt equals !== )
  console.log('isnt demonstration')

See the Pen Coffeescript gotchas (part 2): operators and aliases by John Tsevdos (@tsevdos) on CodePen.

You can also use the not keyword and get rid of Javascript’s exclamation mark (!) operator. Much more readable!

if not false # compiles as if (!false) in Javascript
  console.log('not demonstration')

See the Pen Coffeescript gotchas (part 2): operators and aliases by John Tsevdos (@tsevdos) on CodePen.

Want to make it even more readable? You can even replace the if not statement with the much more descriptive  unless keyword. It makes more sense in some cases:

# if not === unless

person =
  isRunning : false,
  startRunning : ->
  	console.log('start running!')

if not person.isRunning

unless person.isRunning

See the Pen jKLCH by John Tsevdos (@tsevdos) on CodePen.

Finally, you can forget boolean operators such as double ampersands (&&) and the double vertical bars (||) and start using the much more convenient and and or keywords. The real fun starts when you combine all these new keywords. Writing Javascript becomes as easy as english!

name = 'John'
sex  = 'male'
isCool = true

if name is "John" and sex is "male" # compiles as if ( name === "John" && sex === "male" )
  console.log('do something')

if name is "John" or isCool is true # compiles as if ( name === "John" || isCool === true )
  console.log('do something else')

See the Pen JwuiD by John Tsevdos (@tsevdos) on CodePen.

Ternary Operator

The ternary Operator in CoffeeScript looks a bit tricky at first, and in my opinion is probably the only operator that actually looks better in plain good old Javascript, but in case you need to use it, it looks like this:

maxValue = 10
minValue = 1

value = if 10 > 0 then 5 else 15 # value = 5


See the Pen zKaqC by John Tsevdos (@tsevdos) on CodePen.

CoffeeScript’s question mark operator

This is a unique CoffeeScript feature that checks if a variable (or property) has a value. So it basically tests if the value isn’t null or of type undefined. Keep in mind that this is not testing if a value is “falsey” (like a empty string, number 0, empty array, etc.). For more details on “truthy” and “falsy” values have a look at this excellent article on Sitepoint.

if name? # compiles as if ( name !== null || name !== "undifined" )
  document.write('Safely use name value.')

See the Pen wihJj by John Tsevdos (@tsevdos) on CodePen.

You can also use this feature on object properties or when you want to check if the value isn’t null or of type undefined. Have a look at the examples below and discover a nicely added feature that will save you a lot of typing…

person =
	name: 'John'
console.log( person?.name )

nullName = null
nullName?= "Johnny"

console.log( nullName )

nullName = null
otherName = nullName ? "Yiannis"

console.log( otherName )

See the Pen GEksz by John Tsevdos (@tsevdos) on CodePen.

The OR operator (on value assignments)

It looks better and more compact…

name = false # falsy value

name ||= "John" # name || (name = "John");


See the Pen pmfBz by John Tsevdos (@tsevdos) on CodePen.

Chaining comparison

Another CoffeeScript only feature. If your condition is between a range you can finally combine them, just like in algebra. Nicely done.

x = 8

if 0 <= x <= 10 # compiles to if ( 0 <= x  && x <= 10 )

See the Pen Fhqwr by John Tsevdos (@tsevdos) on CodePen.

As you can see CoffeeScript can be very expressive and in many cases you can write code that is as expressive as english! The well chosen aliases make the entire experience more fun and let you focus more on problem solving than on typos and missing curly braces.

If you like this article, stay tuned because the following CoffeeScript articles will be mind blowing…

CoffeeScript gotchas (part 1): Comments, strings, booleans, arrays and functions

In the last couple of months I took some time to learn and work on a CoffeeScript project. Writing CoffeeScript is a lot of fun, and if you know plain Javascript you already know most of the Coffeescript syntax – just start removing all the syntax cluttering like semicolons, parenthesis and square brackets and suddenly you are writing Coffeescript!

The really cool stuff begins when you dig a bit more into the language. There’s some nice demonstrations of features that I had to learn the hard way.

Before jumping into these, have a look at the well-written, free on-line book Coffeescript Cookbook. This excellent resource saved me a lot of time in many situations.

Update: Table of contents


You can have single-line and multi-line comments in CoffeeScript. Always keep in mind that during compilation, the compiler will completely ignore the single line comments (they wont appear in your final Javascript file) but will keep the multi-line comments intact. In the Codepen examples below you can click the “view compiled” link to see the generated JS code and the result tab to see the result (if any)…

# Single-line comment
Multiline comment

See the Pen CoffeeScript gotchas (part 1): Comments by John Tsevdos (@tsevdos) on CodePen.

String Interpolation

Probably the best feature Coffeescript provides! You can finally do things like this:

name = "John"
greeting1 = "Hello, #{name}!" # -> Hello, John!
greeting2 = 'Hello, #{name}!' # -> Hello, #{name}!

document.write greeting1
document.write '
document.write greeting2 

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Keep in mind that double quotes are needed to compile correctly. You can even use functions!

mrFunc = (name) -> "Mr. " + name
message = "Hello, #{mrFunc 'John'}"

document.write message

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.

Heredoc (multiline strings)

You can also use Heredocs. They even support interpolation!

multiline = """
This is 
a multiline
of #{3+2}

document.write multiline

See the Pen CoffeeScript gotchas (part 1): Strings by John Tsevdos (@tsevdos) on CodePen.


Not much news here, apart from some syntax goodies… You can use true with two more keywords, yes and on and you can use false with the opposites, no and off. Sometimes it makes more sense to use these keywords instead of the normal true/false.

# true === yes === on
if true
  document.write 'true
if yes
  document.write 'yes

if on
  document.write 'on


# false === no === off
if !false
  document.write 'false
if !no
  document.write 'no

if !off
  document.write 'off

See the Pen CoffeeScript gotchas (part 1): Booleans by John Tsevdos (@tsevdos) on CodePen.


CoffeeScript allows a very convenient syntax to create specific array ranges. You can create any range using the two dots syntax (inclusive range, which simply means that it will include the last value). Adding three dots instead excludes the last value (exclusive range). Finally you can use reverse ranges the same way. Have a look at the examples, they are much easier than they sound…

range1  = [0..10]  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range2  = [0...10] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range20 = [20..0]  # [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

See the Pen CoffeeScript gotchas (part 1): Arrays by John Tsevdos (@tsevdos) on CodePen.

Functions default values

One of the coolest and most usable CoffeeScript features is the default values on functions. Instead of checking if a value exists, etc. you can simply apply the default value right next to the parameter.

greeting = (name = "friend") -> 
  "Hello #{name}"

document.write greeting('John')
document.write '<br />'
document.write greeting()

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

IIFE – Immediately Invoked Function Expressions

Another tricky part when start to learn CoffeeScript is how you write an IIFE. The syntax is a bit tricky, so have a look below (keep in mind that only CoffeeScript 1.3 and above supports default values on IIFE).

do (doc = document, jQuery = $) -> 
  document.write "IIFE magic"

See the Pen CoffeeScript gotchas (part 1): Functions by John Tsevdos (@tsevdos) on CodePen.

Stay tuned for more CoffeeScript 😉

Gulp boilerplate for web designers

Two weeks ago, I published a Grunt.js boilerplate with common tasks for web designers. This week I’m trying out the new kid on the block, gulp. Gulp is also a node-based task manager, but it works a bit different than Grunt. It works with streams and pipes, making it very fast and easy to understand. I strongly recommend you have a look at this eye-opening presentation on gulp to better understand how it works and why it’s here to stay.

My gulp boilerplate has more or less the same features as my Grunt boilerplate. To mention a few :

If you want to learn more about how gulp works, feel free to have a look at the repository. Also if you have any recommendations or comments feel free to pull, fork, star etc. 😉