CopyPastehas never been so tasty!

Cleaner Javascript with CoffeeScript in Ruby on Rails applic

by stalinthangaraj

  • 0
  • 0
  • 0
97 views

Javascript files often get too large and messy or as DHH would say, "become like a junk-drawer" as

the application grows. Asset Pipeline was introduced in Rails from version 3.1 onwards to help

segregate javascript into smaller files according to the business logic. There were several other

features which were introduced as part of Asset Pipeline; we will cover those in a future article. In

this article we will concentrate on the javascript pre-processor CoffeeScript.

 

CoffeeScript is to Javascript, as SASS is to CSS and HAML is to HTML, it compiles into Javascript.

It adds syntactic sugar to enhance JavaScript's conciseness and readability. It compiles one-to-one

into the equivalent Javascript, and there is no interpretation at runtime. Commas, parenthesis and

curly brackets are optional.

 

CoffeeScript makes JS simpler by fixing lot of confusing and verbose syntax and making it easier to

read. It also brings Object Oriented Programming concepts to JS and typically takes 30-40% lesser

lines of code. Let's take a look at some of the new features available through CoffeeScript.

 

Types

Number: For very big or very small numbers, ‘scientific’ notation can be used, like 1.23e8

 

String: Double quoted strings can contain interpolated values, similar to Ruby, like

"5 + 9  = #{5 + 9}" # => 5 + 9 = 14

A string can span multiple lines to help avoid overly long lines in the program but the line breaks

are not shown in the output.

Triple-quoted strings (heredocs) can be used for strings that span multiple lines where the line

breaks are preserved in the output.

Boolean: true can be written as yes or on and false as no or off.

Function: Functions are defined by an optional list of parameters in parentheses, an arrow, and the

function body. Parentheses and braces can be dropped because indention (1 tab or 2 spaces) can be

used instead to denote blocks of code, like: square = (x) -> x * x

While calling, the parentheses can be left out when values are passed. The value of the last

statement in the function is retuned as the value of the function; it can also be explicitly specified

using return keyword.

 

Operators

Almost all the generic arithmetic, logic and unary operators are supported. It also provides some

aliases for better readability: is for ===, isnt for !==, not for !, or for ||, @ for this and of for in.

Existential Operators: Quite similar to Ruby, ? is the existential operator. It returns true unless

something is null or undefined, like alert 'it exists!' if cupsOfCoffee?

It can be used in existential assignment form, ?= which will only assign to a variable that is either

null or undefined, which is similar to ||= operator in Ruby, like cupsOfCoffee ?= 0

It can also be used similar to try of Ruby, when combined with a 'dot'. So, instead of

object.element we can write object?.element if object is defined then it returns the value of element, otherwise it returns undefined instead of an error.

 

Comments

Similar to Ruby, single hash (#) can be used for single line comments. Multi line comments can be

added using triple hash (###), so all lines encompassed between two triple hashes are treated as

comments.

 

Control-flow

Conditional statements can be written without parenthesis and brackets. Multi-line conditionals are

delimited by indentation.

Switch: This works similar to Ruby, the format is: switch condition, when clauses, else the default

case, like

    message = switch cupsOfCoffee

when 0 then 'Asleep'

when 1 then 'Awake'

else 'Dangerous'

Ternary: There is no explicit ternary statement in CoffeeScript. But it can be achieved by using if.. 

then.. else.., like if age < 18 then alert 'Adult' else alert 'Child'

 

Arrays

Similar to Ruby, Array is collection of data and numbering the array elements starts from 0.

Ranges also create arrays of all elements between the start value and end value. It can be defined

using two-dot (..) operator which includes start and end value or using three-dot (...) operator which

excludes the end value, like [1..4] # => [1, 2, 3, 4] and [1…4] # => [1, 2, 3]

 

Loops

In addition to forEach method, CoffeeScript also supports Ruby like, "for element in elements"

syntax. It can also be combined with conditionals and custom interval, like:

for city in cities when city isnt 'Bangalore'

even_numbers = (number for number in [0..12] by 2)

 

Objects

Objects are key, value pairs like hashes in Ruby. Objects can be created using indentation instead of

explicit braces, similar to YAML, like:

city =

  name: 'Bangalore'

  state: 'Karnataka'

 

Similar to Arrays, we can loop over objects as well, using for key, value of object syntax, like:

for name, state of cities

 

Splats

For variable arguments in a function, we can use '...' commonly called splats. Splats can be used for

function definition as well as invocation, making variable numbers of arguments, like:

searchLocations = (brand, cities...) ->

  "Searching for #{brand} in #{cities.join(',')}"

 

params = ['Starducks', 'Orlando', 'Winter Park']

searchLocations(params...)

 

Object Orientation

CoffeeScript provides a basic class structure that allows to: name a class, set the superclass, assign

properties, and define the constructor, like:

class Animal

    constructor: (@name) ->

    move: (meters) -> alert "moving #{@name}m."

 

Keyword extends can be used to inherit from a base class and super function can be called to

invoke the base class method, like:

class Horse extends Animal

    move: ->

      alert "Galloping..."

super 45

 

JQuery

jQuery’s .ready() event handler can be used in CoffeeScript simply by using jQuery ->.  If no other

libraries are using $, we can use like this: $ ->.

 

Please refer to the official site for the full documentation. You can also watch a brief RailsCast for

usage with Rails. For more examples, you can refer to the slides used for internal training.

 

Get more information on: Ruby On Rails Programmer

For more information visit: Mobile Applications Development

Add A Comment: