Why should I learn Coffee-Script?
- Rails 3.1 is shipping with coffee script.
- It adds a fine syntactic sugar to java script making your code even more beautiful and terse.
- Easy to learn if you already are working on scripting languages such as ruby or php.
I am not going to blog about coffee scripting as it is already very well documented. However, it might help to lay down steps to quickly integrate it in your rails application. So here is the 10 minutes drill to it.
Introducing Coffee-Script in you rails 3 application
- Add the necessary gems to your gemfile
gem 'coffee-script' gem 'barista' #It will auto compile your .coffee files into .js files. gem 'therubyracer', :require => nil #If you do not have nodesjs installed. Install node.js gem 'json'
- Configure barista for your application.
rails generate barista:install
- Know that you have a
config/initializers/barista_config.rbfile for customization. You do not need to touch it yet.
- Add in your first coffee script file in there named
welcome.coffeewith the below code:
$(document).ready -> alert("Welcome to the world of coffee scripts");
- Add below code in one of your erb files or application layout to see inline coffee script:
<script type="text/coffeescript"> firstFunction = -> alert('I am inline function') firstFunction(); </script>
- Start your rails app and goto http://localhost:3000
- Know that barista will start logging in your console window.
- You can also use jquery with coffee-script syntax
<div id="effects">Test to see if it works with jQuery</div> <script type="text/coffeescript"> $(document).ready -> $('#effects').fadeOut('slow', -> $('#effects').fadeIn('slow') ) </script>
Enjoy Coffee Scripting. Try it!
Founder CEO, Idyllic.
Follow me on Twitter