Logo

Who is talking?

Archive

Ubuntu 14.04.2 (32 bit) installation with VirualBox on Windows

over 2 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

In my current project, I happen to work on Windows again (sadly). But there is no point in beating the bush, when you know you have to get the job done anyway. I preferred to embrace constraints and take it up as a challenge.I started exploring options and if you are in similar situation, you may want to follow below steps.Before I proceed, let me share my system configuration:Lenovo latest seriesRAM 8GHard Disk 120GIntel processor 64 bit Crucial part: No admin level accessVMware Player + Ubuntu did not work for meI downloaded and installed VMware Player: http://www.vmware.com/products/playerI picked up Ubuntu 14.04.2 a 64-bit OS: http://www.ubuntu.com/download/desktopThen I got error in installation: SMBus base address uninitialized - upgrade BIOS or use force_addr=0xaddrSince I had no admin level access, I give up here on VMware + UbuntuVirtualBox + Ubuntu worked for me:1. Download VirtualBox x86 version (not amd64)Installation is simple, step-by-step through wizard.2. Download Ubuntu 32-bit3. Create Virtual Machine using UbuntuI just took step-by-step, screenshot, if this helps to someone. Select 'Ubuntu-downloaded-image4. 'Install' rather than 'Try Ubuntu'Now, when setup a new Virtual Machine, Boot from the downloaded Ubuntu 32-bitSelect 'Install' option, which might take extra 10-15 mins but it's worth it. 'Try Ubuntu' will not save anything installed once you log out, I burnt my hands there :( 5. When prompted, select 'Erase data and create partition' since, it's only doing everything in VirtualBox and no harm to your system's configuration.6. Once Ubuntu is installed, you will see 4x3 screen, which is very small for development work. Let's change it.I followed: http://askubuntu.com/a/451879/398044Simply run on terminal:sudo apt-get install virtualbox-guest-dkms \virtualbox-guest-utils virtualbox-guest-x11Then in VirtualBox Settings select 'InsertGuest Addition CD image' Once this is done, restart system.7. Slowness of VirtualBox + UbuntuI noticed the Ubuntu Virtual Machine was very slow, so I enabled 3-D acceleration8. Share folder bi-directional between Windows and VirtualBox's Ubuntu systemRun below command to fix permission denied on 'shared' directory in Ubuntu:adduser xxxxxxx vboxsf 9. That's it!If you are in similar situation, give these steps a try and add more if some steps do not work here.

What is 'this' in Javascript?

over 2 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Disclaimer: This is not a new topic and there are several authors/writers have explained it in various ways. My intention to write this post is to understand it better, in my own words. JavaScript is a mystery language for me. One of the most confusing feature is, what is the value of this in a function. When I learnt it, I found I develop good sense of understanding closures too.Let’s try to understand this behavior. The value of this is dynamic and it depends on how a function is invoked (reference: "JavaScript: The Good Parts”).Method Invocation pattern: When a function is defined as a part of current object’s property and called on the object via ‘.’ (dot), then this always refers to the current object, here is an example:var myObj = {  value: 5,  square: function(){    console.log(this); // this refers to current object i.e. myOb    console.log(this.value); // this.value is 5 here    return this.value * this.value; // return 5 * 5 = 25  }}myObj.square(); // Method InvocationFire up your browser’s (Chrome / Safari / FF) developer tool and see it in action.Function Invocation pattern:  When function can be called without object’s reference, it’s called ‘Function Invocation’. Notice that previously we referenced myObj, when calling square function. Here is a different variation using 'Function Invocation’, pay attention to internalFun():var myObj = {};myObj.square = function(a){  console.log(this); // this is still referring to myObj as here   // we are adding square function, as a property to the myObj  console.log(a); // The value we passed to square function here  var internalFun = function(b){    console.log(a); // value of a is still accessible, ‘closure’ feature    console.log(b); // value of b is what is passed to this internalFun function    console.log(this); // Surprise! It’s not myObj even though it is in ‘closure’,     // instead of window, why?  }  internalFun(a + 5); // Function Invocation: value of a is same, which is passed directly  return a * a; // square value}myObj.square(5) // Method InvocationinternalFun(6 + 5); // Function Invocation, but invoked outside of the closure hence ‘Reference Error: internalFun() is not definedThis is the most confusing nature I saw for this. Why is such a behavior? Let’s look little deeper in console log response.We see that this refers to ‘window’ object. Even though internalFun() is inside square closure, 'it refers to global object’. Reason is, since it is not tied up to any object, it cannot hang in middle :) It needs to reference to something and that something is a kind of ‘default’ in JavaScript language, which is known as 'global object'.Note that if you try to call outside the square closure, you will see internalFun() is ‘undefined'Constructor Invocation: This is more obvious than Function Invocation. When you create an instance of an object, value of this becomes 'new instance'. The object which can be instantiated has to be an 'anonymous function'. Let’s see an example.var MyObj = function(){  console.log(this); // If we invoke directly this function via Function Invocation,                              // it will reference to global object                              // If we invoke via ‘new’, this refers to newly constructed object,                             // in our case ‘squareOfTwo'  this.value = 5;}// adding method to prototypeMyObj.prototype.square = function(a){  console.log(a); // ‘undefined' if not passed as parameter  console.log(this); // this refers to MyObj  var a = (a == undefined ? this.value : a); // get a default value from constructor  return a * a;}MyObj(); // This refers to global object// MyObj.square(); will throw error 'undefined function',// since prototype functions can be accessed by constructors only.squareOfTwo = new MyObj();squareOfTwo.square(2);squareOfFive = new MyObj();squareOfFive.square();Apply Invocation: This is very powerful way to invoke any method on objects, even though those objects may or may not have this method. What will be value of this here? This is the most definitive invocation style where ‘you’ know the value of this and actually you set what would be value of this.‘apply’ is a special method in JavaScript, which takes two parameters, value of this and array of parameters.value of this is null:var add.apply(null, [1,2,3]) // value of ‘this' is passed as null to add function and                                         // [1,2,3] are arguments to add integers.value of this is user defined:var Hello = function(){  this.greeting = 'Hello';  this.message = 'World';}Hello.prototype.sayHello = function(){ return this.greeting + ' ' + this.message; }// ‘this’ will be the object we are applying the function on, e.g. ‘hi'var hi = { greeting: 'Hi', message: 'Buddy!' }Hello.prototype.sayHello.apply(hi); // value of ‘this' we are passing as ‘hi', output: "Hi Buddy!”SummarySo, now I understood that:Method invocation, this refers to current objectFunction invocation, this refers to global objectConstructor invocation, this refers to new objectApply invocation, this refers to the object we pass to apply function Please share your thoughts/feedback/perspectives.

how to clear redis and solr indexes working on local setup

over 2 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

As I am working in an app which needs keys to be stored in Redis and index data in Solr, due to redis eviction policy, sometimes keys gets evicted, but index in solar remains same, which result in confusing local behavior for me.To clear local redis cache copy, I do it from redis-cli$ redis-cli127.0.0.1:6379> FLUSHDBOK127.0.0.1:6379> FLUSHALLOK127.0.0.1:6379> exitTo remove solr indexes, I use curl:$ curl http://localhost:8982/solr/update?commit=true -d '*:*'

Addressbook application with SailsJS

about 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

SailsJS is great for realtime applications and as I play more with it, I like it more. What is interesting to me is, how easy/difficult to use/create APIs and query language in SailsJS.Problem statementWith this intent I would like to show how to build a small Address Book application (finder), that allows users to find contacts by name, phone or address.My Approach (build it in 60 mins!)Install node.js and sails.js (10 mins)Create new Sails application (5 mins)Understanding routes and defining custom routes (5 mins)Define Schema and perform CRUD operations (10 mins)Setup custom Layout (with bootstrap) and kill the default one (10 mins)Get search form ready (10 mins)Add search action to controller (5 mins)Add finder query in model (5 mins)Demo time!P.S. Team @kiprosh did it in 40 mins :)Install node.js and sails.js (10 mins)It literally took me 7 mins to install node.js on mac and 3 mins to install sails.js :)Create new Sails application (5 mins)Run below command to install new sails application, let's say address book:sails new address bookand start sails serversails liftTip#1 : You can do sails console too :)Tip#2 : Every time you make a change in controller/model/anything-in-api , you need to restart the server OR you can use forever as "forever -w start app.js", but that's for later :)Understanding routes and defining custom routes (5 mins)If you are familiar with Rails, it will be piece of cake for you. Checkout addressbook/config/routes.js and add custom routes in that file.Here are tips for static routes:To show only view, let's say root page of our application:'/': {    view: 'addressbook/index'  }, To define actions for get/post/put/delete http verbs:'get /addressbook/search': 'AddressbookController.search'// where addressbook/search route will be served by AddressbookController's search actionAlso checkout crud blueprints in the same routes.js file.Define Schema and perform CRUD operations (10 mins)You can add adapter of your favorite database to config/adapters.js. Default is module.exports.adapters = { 'default': 'disk', disk: { module: 'sails-disk' // this database is accessible at addressbook/.tmp/disk.db file },....}Defining your models are even simpler. Let's say you want to create addressbook/api/models/AddressBook.js model, here is how you can define it's schema:module.exports = { attributes: { name: 'string', address: 'string', phone: 'string' //Any instance method would go here }, //Any class method would go here...} To do crud operations, I would encourage use chrome extension called postman. Simply install this extension and launch app. With AddressBook model created, in postman you can do things like:GET http://localhost:1337/addressbook // to list all contactsPOST http://localhost:1337/addressbook // to create a contact, add name, address, phone and post itDELETE http://localhost:1337/addressbook?id=3 // to delete a contact with id = 3With postman handy, I would skip building CRUD UI and move over to search feature.Setup custom Layout (with bootstrap) and kill the default one (10 mins)Layout of our application resides in addressbook/views/layout.ejs, so go and open it up. You can download bootstrap and add it to link css and include bootstrap.jsAdd CSS files in addressbook/assets/styles directory,  add JS files in addressbook/assets/js directory and give links in layout.ejs ...<script src="/js/bootstrap.min.js" type="text/javascript"></script><script src="/js/app.js" type="text/javascript"></script><script src="/js/custom.js" type="text/javascript"></script>Somewhere near body tag you would notice <%- body %>, this will include view file for current controller/action. Since in routes section above, we have added default(root) route asview: 'addressbook/index'We need to add something to addressbook/views/index.ejs file, so that by default our custom text would appear, let's say:My Addressbook Note: 'ejs' is templating engine and you can use engine of your own choice as well.Get search form ready (10 mins)Add search form to addressbook/views/addressbook/index.ejs add your own way of building a form.Add search action to controller (5 mins)Add Search action to addressbook/api/controllers/AddressbookController.jsAdd finder query in model (5 mins)Add getSearchResults function to model addressbook/api/models/AddressBook.js I am using 'contains' search on name, address and phone, you can play with it and do something like, starts with, exact match, etc :)Demo time!It would be great if you can show a demo app or may be share repos, so that even I can learn from it :) Mine is here: https://github.com/gouravtiwari/addressbookI hope you enjoyed building this toy application. As I said SailsJS is great for realtime apps, so go ahead and play with it.

Addressbook application with SailsJS

about 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

SailsJS is great for realtime applications and as I play more with it, I like it more. What is interesting to me is, how easy/difficult to use/create APIs and query language in SailsJS.Problem statementWith this intent I would like to show how to build a small Address Book application (finder), that allows users to find contacts by name, phone or address.My Approach (build it in 60 mins!)Install node.js and sails.js (10 mins)Create new Sails application (5 mins)Understanding routes and defining custom routes (5 mins)Define Schema and perform CRUD operations (10 mins)Setup custom Layout (with bootstrap) and kill the default one (10 mins)Get search form ready (10 mins)Add search action to controller (5 mins)Add finder query in model (5 mins)Demo time!P.S. Team @kiprosh did it in 40 mins :)Install node.js and sails.js (10 mins)It literally took me 7 mins to install node.js on mac and 3 mins to install sails.js :)Create new Sails application (5 mins)Run below command to install new sails application, let's say address book:sails new address bookand start sails serversails liftTip#1 : You can do sails console too :)Tip#2 : Every time you make a change in controller/model/anything-in-api , you need to restart the server OR you can use forever as "forever -w start app.js", but that's for later :)Understanding routes and defining custom routes (5 mins)If you are familiar with Rails, it will be piece of cake for you. Checkout addressbook/config/routes.js and add custom routes in that file.Here are tips for static routes:To show only view, let's say root page of our application:'/': {    view: 'addressbook/index'  }, To define actions for get/post/put/delete http verbs:'get /addressbook/search': 'AddressbookController.search'// where addressbook/search route will be served by AddressbookController's search actionAlso checkout crud blueprints in the same routes.js file.Define Schema and perform CRUD operations (10 mins)You can add adapter of your favorite database to config/adapters.js. Default is module.exports.adapters = { 'default': 'disk', disk: { module: 'sails-disk' // this database is accessible at addressbook/.tmp/disk.db file },....}Defining your models are even simpler. Let's say you want to create addressbook/api/models/AddressBook.js model, here is how you can define it's schema:module.exports = { attributes: { name: 'string', address: 'string', phone: 'string' //Any instance method would go here }, //Any class method would go here...} To do crud operations, I would encourage use chrome extension called postman. Simply install this extension and launch app. With AddressBook model created, in postman you can do things like:GET http://localhost:1337/addressbook // to list all contactsPOST http://localhost:1337/addressbook // to create a contact, add name, address, phone and post itDELETE http://localhost:1337/addressbook?id=3 // to delete a contact with id = 3With postman handy, I would skip building CRUD UI and move over to search feature.Setup custom Layout (with bootstrap) and kill the default one (10 mins)Layout of our application resides in addressbook/views/layout.ejs, so go and open it up. You can download bootstrap and add it to link css and include bootstrap.jsAdd CSS files in addressbook/assets/styles directory,  add JS files in addressbook/assets/js directory and give links in layout.ejs ...<script src="/js/bootstrap.min.js" type="text/javascript"></script><script src="/js/app.js" type="text/javascript"></script><script src="/js/custom.js" type="text/javascript"></script>Somewhere near body tag you would notice <%- body %>, this will include view file for current controller/action. Since in routes section above, we have added default(root) route asview: 'addressbook/index'We need to add something to addressbook/views/index.ejs file, so that by default our custom text would appear, let's say:My Addressbook Note: 'ejs' is templating engine and you can use engine of your own choice as well.Get search form ready (10 mins)Add search form to addressbook/views/addressbook/index.ejs add your own way of building a form.Add search action to controller (5 mins)Add Search action to addressbook/api/controllers/AddressbookController.jsAdd finder query in model (5 mins)Add getSearchResults function to model addressbook/api/models/AddressBook.js I am using 'contains' search on name, address and phone, you can play with it and do something like, starts with, exact match, etc :)Demo time!It would be great if you can show a demo app or may be share repos, so that even I can learn from it :) Mine is here: https://github.com/gouravtiwari/addressbookI hope you enjoyed building this toy application. As I said SailsJS is great for realtime apps, so go ahead and play with it.

How to introduce BatmanJS to existing Rails Application

about 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

While evaluating BatmanJS for one of the biggest application here @Kiprosh, I found it very much Rails like and started drawing parallels when I was doing MVP with Rails and BatmanJS.Note: This is not a tutorial for getting started or building rails app with BatmanJS. I personally like Zack hubert’s blog and Batman for SuperHeroesIf you are book lover, you will certainly like cookbookI am sharing my experience on possible approaches/concepts to move view-layer from existing Rails application to BatmanJS.Routes in BatmanJSIt is very straight-forward in BatmanJS. In the main JS file you can define routes, just as you do in Rails, here is an (example) : class Realvolve extends Batman.App # @resources 'products' # @resources 'discounts', except: ['edit'] # @resources 'customers', only: ['new', 'show'] # @resources 'blogs', -> # @resources 'articles' # @resources 'pages', -> # @collection 'count' # @member 'duplicate' Rails partials to data-partials in BatmanJSOne of the easiest way to translate partials into BatmanJS is using data-partial:  "data-partial" => "posts/_form"You can also use ‘source’ in views: // In views/layouts/left_pan_view.js.coffee class Realvolve.LeftPaneView extends Batman.View source: 'layouts/_left_pane'// In html/layouts/_left_pane.htmlSome html code goes here…Where would I start?I started with a small piece, mainly from layouts. While whole application is being served from Rails, I picked one page where view is being drawn by BatmanJS. With this approach, I not only got a chance to play with BatmanJS, but I understand how existing app’s view layer can be moved to BatmanJS as well.How about Ajax calls from view?Unfortunately, there is no direct documentation on this, but that is the fun part to explore it. Later it turned out to be very simple, by making use of data-event-, here is an example:// Somewhere in my search.html file// In my controller/search_controller.js.coffeeclass Realvolve.SearchController extends Realvolve.ApplicationController routingKey: 'search' // controllers in Batman can make AJAX calls too (Batman.request)! index: (params) -> new Batman.Request url: "/search?search=#{params.value}" success: (data) -> return data error: (err) -> return err return undefined// this would return search results(may be JSON) and later you can use this to show results, by using data-foreach binding.Challenges?Main challenge I see is converting pretender logic into BatmanJS. Pre-render is great for rails applications, but it also makes code a little convoluted and makes it difficult to change. Off-course comparison with AngularJS/EmberJS/etc will always be there. I personally prefer AngularJS, because of ease of learning and simpler syntax/structure of code than BatmanJS.

Building static web applications with github

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Recently I saw a lot of ads to create web applications in few bucks! One of my friend Sachin Sharma (who is a student) asked me if it is easy to create a web-site and I said basic one is really simple. You don't need to know a lot of stuff. So, here I am sharing quick and easy steps if you want create your own it is really simple and easy in five steps:New RepoGithub signup and login: First of all you need to signup and sign-in to github.com. Create a github repo: Once you are signed-in, on home page create a new reposity (+ New Repository) as <your-github-account-name>.github.io (New Repo). Do not select 'Initialize this repository with a README' and on next screen follow 'Create a new repository on the command line', for this you need to install github on your system, follow this link for easy steps (Windows guide /   Mac guide). Once you are done with setup, clone the git repo you created to your system.Find a free template for your need and download: There are plenty of websites which offers free templates. You just need to download it to cloned repository(from previous step) and add your content and replace few images to give it personal touch. Here are few websites:bootstrapzero.comstartbootstrap.combootswatch.combootstrapstage.comUpdate HTML, CSS and JavaScript with relative path name: For example, if image path is /home/gourav/new-webapp/app/images/logo.jpg then change it to app/image/logo.jpgCommit and push changes to github: As soon as you commit and push your changes then go and launch this url http://<your-github-account-name>.github.ioThat's it!

Building static web applications with github

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Recently I saw a lot of ads to create web applications in few bucks! One of my friend Sachin Sharma (who is a student) asked me if it is easy to create a web-site and I said basic one is really simple. You don't need to know a lot of stuff. So, here I am sharing quick and easy steps if you want create your own it is really simple and easy in five steps:New RepoGithub signup and login: First of all you need to signup and sign-in to github.com. Create a github repo: Once you are signed-in, on home page create a new reposity (+ New Repository) as <your-github-account-name>.github.io (New Repo). Do not select 'Initialize this repository with a README' and on next screen follow 'Create a new repository on the command line', for this you need to install github on your system, follow this link for easy steps (Windows guide /   Mac guide). Once you are done with setup, clone the git repo you created to your system.Find a free template for your need and download: There are plenty of websites which offers free templates. You just need to download it to cloned repository(from previous step) and add your content and replace few images to give it personal touch. Here are few websites:bootstrapzero.comstartbootstrap.combootswatch.combootstrapstage.comUpdate HTML, CSS and JavaScript with relative path name: For example, if image path is /home/gourav/new-webapp/app/images/logo.jpg then change it to app/image/logo.jpgCommit and push changes to github: As soon as you commit and push your changes then go and launch this url http://<your-github-account-name>.github.ioThat's it!

Benefits of SOA in complex Rails applications

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Often I saw that initial POC(Proof of concept) rails apps are sleek, sweet and beautiful from code perspective. But as requirements grow, it gets complex and starts falling apart. There could be several reasons:I was using twitter-bootstrap-rails gem but now I need foundation or may be my own custom look and feelI need to do lot of customization/monkey-patching as one feature needs gem 'X' which doesn't work on Oracle and my whole app is on Oracle/MySQL/etcEvery time I change something, it breaks application (including views).Sometimes we accommodate changes and integrate another DB/technology, but it leaves code smells.What if tomorrow client requires new NoSQL database? Can I integrate it without breaking lot of features?Answer is SOARecently on a project I, along with colleagues, implemented SOA (Service Oriented Architecture) in Rails application and I am fascinated by Rails contributors again!Rails provide a gem called: 'rails-api', a nice extraction from Rails library to provide exactly what is needed for SOA.WIth Rails API:BAD: You will miss rails views/form-helpers/view-helpers while using rails-api gem. Good news is, you will get a chance to implement it in HTML/JS with your favorite JS framework, e.g. AngularJS etc.GOOD: You only need to care about REST-ful APIs and expect JSON objects in response.BEAUTIFUL: Backend and frontend will communicate via REST-ful APIs, so anytime you make a change in backend/change database, view will not bother. You can even change whole backend and implement backend in a different language/framework! Same goes with frontend, if you don't like AngularJS someday, you can use SailsJS etc.SummaryImplementing your application on SOA doesn't require an overhaul, if your application has legacy code. You can change one unit at a time and replace it with one service. Although it is not silver bullet, but this architecture-design, allows flexibility on picking technology, at the same time, you application can be still manageable. Implementing a new feature means just adding/modifying a single service :)

Benefits of SOA in complex Rails applications

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Often I saw that initial POC(Proof of concept) rails apps are sleek, sweet and beautiful from code perspective. But as requirements grow, it gets complex and starts falling apart. There could be several reasons:I was using twitter-bootstrap-rails gem but now I need foundation or may be my own custom look and feelI need to do lot of customization/monkey-patching as one feature needs gem 'X' which doesn't work on Oracle and my whole app is on Oracle/MySQL/etcEvery time I change something, it breaks application (including views).Sometimes we accommodate changes and integrate another DB/technology, but it leaves code smells.What if tomorrow client requires new NoSQL database? Can I integrate it without breaking lot of features?Answer is SOARecently on a project I, along with colleagues, implemented SOA (Service Oriented Architecture) in Rails application and I am fascinated by Rails contributors again!Rails provide a gem called: 'rails-api', a nice extraction from Rails library to provide exactly what is needed for SOA.WIth Rails API:BAD: You will miss rails views/form-helpers/view-helpers while using rails-api gem. Good news is, you will get a chance to implement it in HTML/JS with your favorite JS framework, e.g. AngularJS etc.GOOD: You only need to care about REST-ful APIs and expect JSON objects in response.BEAUTIFUL: Backend and frontend will communicate via REST-ful APIs, so anytime you make a change in backend/change database, view will not bother. You can even change whole backend and implement backend in a different language/framework! Same goes with frontend, if you don't like AngularJS someday, you can use SailsJS etc.SummaryImplementing your application on SOA doesn't require an overhaul, if your application has legacy code. You can change one unit at a time and replace it with one service. Although it is not silver bullet, but this architecture-design, allows flexibility on picking technology, at the same time, you application can be still manageable. Implementing a new feature means just adding/modifying a single service :)

2013: Year of achievements!!!

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

As I look back to year 2013, it turned out to be an year of achievements, for me on both on personal and professional front!Personally:Ran 10 miles in under 2 hrs(1:56) BSR PhilllyLearnt swimming and practiced, thanks to my father(V K Tiwari) and Sagar Motikhaye Regular physical exercise achieved :)and lot of fun with friends and family!Professionally:Organized a DevDay@TCSReleased multiple ruby gemsAttended first ever JSChannel conferenceRead a very nice book Clean Coder by Uncle BobContributed to various open-source projectsLearnt D3 (still call myself a beginner :) Learnt Angular (again beginner :)Learnt R (coursera)Shared knowledge in BDD, TDD, Ruby, Rails with various teamsLooking forward to 2014 with lots and lots of fun, learning and sharing!

2013: Year of achievements!!!

over 3 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

As I look back to year 2013, it turned out to be an year of achievements, for me on both on personal and professional front!Personally:Ran 10 miles in under 2 hrs(1:56) BSR PhilllyLearnt swimming and practiced, thanks to my father(V K Tiwari) and Sagar Motikhaye Regular physical exercise achieved :)and lot of fun with friends and family!Professionally:Organized a DevDay@TCSReleased multiple ruby gemsAttended first ever JSChannel conferenceRead a very nice book Clean Coder by Uncle BobContributed to various open-source projectsLearnt D3 (still call myself a beginner :) Learnt Angular (again beginner :)Learnt R (coursera)Shared knowledge in BDD, TDD, Ruby, Rails with various teamsLooking forward to 2014 with lots and lots of fun, learning and sharing!

Localizing gem using bundler for different linux environments

almost 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Different linux environments??? Would it happen ever? In theory no, in practical yes!In the current project I have 3 environments:Development/Local (my Mac)Integration/CI environment (SUSE 11 (x86_64))Production (RHEL 5.7)Why these are different, it's not the question, the question is, if I localize gems using bundler (in path-to-app/vendore/cache) how would it pick the right gem for these environments?In the current project, I need to install therubyracer it's latest version (as of now 0.12.0) depends on libv8 (~> 3.16.14.0)When I did bundle install --local, it saved therubyracer-0.12.0.gem and libv8-3.16.14.3.gem files in vendor/cache that worked fine in environment 1 & 3 but failed on 2After comparing environments, I realized that I can easily install libv8 for x86_64 on environment 2 but when I run bundle install it throws this error:Loading ....So, I added two gem in vendor/cache for libv8: libv8-3.16.14.3-x86_64-linux.gem (for environment 2)libv8-3.16.14.3.gem (for environment 1 & 3)and it works! 

Localizing gem using bundler for different linux environments

almost 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Different linux environments??? Would it happen ever? In theory no, in practical yes!In the current project I have 3 environments:Development/Local (my Mac)Integration/CI environment (SUSE 11 (x86_64))Production (RHEL 5.7)Why these are different, it's not the question, the question is, if I localize gems using bundler (in path-to-app/vendore/cache) how would it pick the right gem for these environments?In the current project, I need to install therubyracer it's latest version (as of now 0.12.0) depends on libv8 (~> 3.16.14.0)When I did bundle install --local, it saved therubyracer-0.12.0.gem and libv8-3.16.14.3.gem files in vendor/cache that worked fine in environment 1 & 3 but failed on 2After comparing environments, I realized that I can easily install libv8 for x86_64 on environment 2 but when I run bundle install it throws this error:Loading ....So, I added two gem in vendor/cache for libv8: libv8-3.16.14.3-x86_64-linux.gem (for environment 2)libv8-3.16.14.3.gem (for environment 1 & 3)and it works! 

How to make your Rails::Engine gem compatible with both rails 3.2.x and rails 4.0

almost 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

As I am improvising audit_rails (Rails::Engine gem), this weekend I planned to make it compatible with both rails 3.2.x and rails 4.0. It was not very difficult though.Here was the challenge I faced in this process:First thing I did was get rid of attr_accsessible from model of my gem and I was able to get my gem working with Rails 4 application, but  I started getting warning when used it for Rails-3 app: Can't mass-assign protected attributes errorTo fix this, I tried using protected_attributes gem, but it didn't work. Fortunately, I looked-up for devise and a trick help me find a solution for mass-assignment issue.I checked which version of Rails is in use and if it is Rails-3 then using attar_accessible in model:Loading ....I hope this trick help saving some human hours :)

How to make your Rails::Engine gem compatible with both rails 3.2.x and rails 4.0

almost 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

As I am improvising audit_rails (Rails::Engine gem), this weekend I planned to make it compatible with both rails 3.2.x and rails 4.0. It was not very difficult though.Here was the challenge I faced in this process:First thing I did was get rid of attr_accsessible from model of my gem and I was able to get my gem working with Rails 4 application, but  I started getting warning when used it for Rails-3 app: Can't mass-assign protected attributes errorTo fix this, I tried using protected_attributes gem, but it didn't work. Fortunately, I looked-up for devise and a trick help me find a solution for mass-assignment issue.I checked which version of Rails is in use and if it is Rails-3 then using attar_accessible in model:Loading ....I hope this trick help saving some human hours :)

Re-looking at unit testing of JS Code: Jasmine

about 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Few years back I looked at unit testing of JavaScript code and used BlueRidge Project, which died later. It was painful and I quickly lost interest in testing JavaScript code. Later I used jasmine around the same time and did some unit testing, but again lost the will to write tests for JS code.Here were the pain areas:testing DOM manipulation codeuse of numerous anonymous functionslack of will to write good and testable JS code @sumankpaul really kind of re-introduced me to Jasmine from scratch and I started learning again with the right attitude.Here are some tips from today's learning:Write testable codeMinimum or No DOM manipulation in JS code, DOM manipulation is evilTalking with the DOM, DOM manipulations and actual JS code logic are different concerns and need to have right tools like AngularJS if possible for the same.Onclick should not be attached with many functionAnonymous functions should be changed to named-functionsonClick is not bad to be added on DOM as AngularJS also does the sameSome tools:Flight library for DOM manipulationTesting ajax methods/third party calls:mock = (stub = spyon + return) + expectationsUsing Jasmine:file name has to have 'Spec' otherwise use --matchall flag--autotest to run JS tests like guardMore to learn... 

Re-looking at unit testing of JS Code: Jasmine

about 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Few years back I looked at unit testing of JavaScript code and used BlueRidge Project, which died later. It was painful and I quickly lost interest in testing JavaScript code. Later I used jasmine around the same time and did some unit testing, but again lost the will to write tests for JS code.Here were the pain areas:testing DOM manipulation codeuse of numerous anonymous functionslack of will to write good and testable JS code @sumankpaul really kind of re-introduced me to Jasmine from scratch and I started learning again with the right attitude.Here are some tips from today's learning:Write testable codeMinimum or No DOM manipulation in JS code, DOM manipulation is evilTalking with the DOM, DOM manipulations and actual JS code logic are different concerns and need to have right tools like AngularJS if possible for the same.Onclick should not be attached with many functionAnonymous functions should be changed to named-functionsonClick is not bad to be added on DOM as AngularJS also does the sameSome tools:Flight library for DOM manipulationTesting ajax methods/third party calls:mock = (stub = spyon + return) + expectationsUsing Jasmine:file name has to have 'Spec' otherwise use --matchall flag--autotest to run JS tests like guardMore to learn... 

Rails application server on Windows

over 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

I came across very similar requirements to Rocky Jaiswal, where the requirement was to run rails application on windows box. I decided to use sqlite3 in production mode as there would be very less users (< 100) and no hassle to install sqlite3 database. Overall, here are the things I needed to download:JDK 1.7Jruby 1.7.2Jetty-runner 8.1.8After following Rocky's blog, there were few more steps required. Added warbler to GemfileRun bundle installbundle exec warble config #This will generate config/warble.rb file.Update config/warble.rbRunbundle exec rake assets:precompile #This will precompile rails assetsbundle exec warble #This will create < application-name.war > fileAdd below to database.yml (production section):production:  adapter: sqlite3  database: <%= java.lang.System.getProperty('db') %>Run application on JVM:java -Ddb=/production.sqlite3 -jar jetty-runner.jar < application-name >.war

Rails application server on Windows

over 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

I came across very similar requirements to Rocky Jaiswal, where the requirement was to run rails application on windows box. I decided to use sqlite3 in production mode as there would be very less users (< 100) and no hassle to install sqlite3 database. Overall, here are the things I needed to download:JDK 1.7Jruby 1.7.2Jetty-runner 8.1.8After following Rocky's blog, there were few more steps required. Added warbler to GemfileRun bundle installbundle exec warble config #This will generate config/warble.rb file.Update config/warble.rbRunbundle exec rake assets:precompile #This will precompile rails assetsbundle exec warble #This will create < application-name.war > fileAdd below to database.yml (production section):production:  adapter: sqlite3  database: <%= java.lang.System.getProperty('db') %>Run application on JVM:java -Ddb=/production.sqlite3 -jar jetty-runner.jar < application-name >.war

Rails upgrade from 3.2.9 to 3.2.11

over 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

With extremely critical RoR bug, rails upgrade was imminent in my current project.Here are the steps:Open Gemfile, change:gem 'rails', '3.2.9' to gem 'rails', '3.2.11'From command line, go to root directory:$ bundle update railsTest your app!That's it!

Rails upgrade from 3.2.9 to 3.2.11

over 4 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

With extremely critical RoR bug, rails upgrade was imminent in my current project.Here are the steps:Open Gemfile, change:gem 'rails', '3.2.9' to gem 'rails', '3.2.11'From command line, go to root directory:$ bundle update railsTest your app!That's it!

Audit trails for Rails application: with audit_rails gem

almost 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

In my current project, there is a requirement to audit user actions, most of which are not model crud operations (more or less like omniture, but this is not a replacement to omniture).So, I looked for a gem which allow me to audit user actions from controller/view as opposed to mode crud operation and I ended up writing audit_rails.This gem provides:Audits based on controller actionsLink tracking for external/internal linksUser login actions (once per-day)Export audit report in excelHere is the link to github repo. I hope this will save someone the pain of re-inventing the wheel.

Audit trails for Rails application: with audit_rails gem

almost 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

In my current project, there is a requirement to audit user actions, most of which are not model crud operations (more or less like omniture, but this is not a replacement to omniture).So, I looked for a gem which allow me to audit user actions from controller/view as opposed to mode crud operation and I ended up writing audit_rails.This gem provides:Audits based on controller actionsLink tracking for external/internal linksUser login actions (once per-day)Export audit report in excelHere is the link to github repo. I hope this will save someone the pain of re-inventing the wheel.

imageScience on Ubuntu

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

imageScience on Ubuntu and ruby 1.8.7, should be very simple. What the hack! I spent 1 hour figuring out, simply you need this:sudo apt-get install libfreeimage-devsudo apt-get install libfreeimage3gem install RubyInlineSharing == saving some extra human hours!

imageScience on Ubuntu

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

imageScience on Ubuntu and ruby 1.8.7, should be very simple. What the hack! I spent 1 hour figuring out, simply you need this:sudo apt-get install libfreeimage-devsudo apt-get install libfreeimage3gem install RubyInlineSharing == saving some extra human hours!

Experience at ConFoo

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

It was a wonderful journey to see innovations happening around various technology stacks and a beautiful trip to Montreal, Canada specially in winter (freezing at -5C to -10C).Confoo, 2012 had more than 100 speakers and there were more than 150 sessions in 3 days.Sessions I liked most (my favorite is last one):Continuous Delivery at Speed by Jospeh Wilk, where he talks about trade-offs between fast paced development Vs safe deployment. As a developer we like things to be deployed and released to users quickly and we use latest tools like Jenkins and for CI to deploy as soon as we commit a single line of code. So idea is to have a balance between speed and safety, i.e. zero failure builds and tools like guard can be very useful.How CMS architecture affects dev communities by Julian Egelstaff where he compared architecture of three CMS from PHP: TikiWiki, Xoops and Drupal and saw some patterns on how the communities around these CMS are reacting to the architecture. In a nutshell, "It doesn't seem to matter if you have lot of core developers, but it does matter that your community uses the architectural features of the core code as a foundation of their systems." Drupal has lot of flexibility as it has very smaller modules which can be plugged and play, while Xoops has "big module" architecure, which allows less flexibility and TikiWiki community is smaller, but the architecture is not modular and more or less like wiki way which makes it hard to extend.Make your project SOLID! by Tobias Schlitt It was very interesting to see how simply SOLID principles help in shaping your application.I am listing down only principals here as explanation would be a separate blog on this topic :)Single responsibility principleOpen/closed principleLiskov substitution principleInterface segregation principleDependency inversion principle (kind of principle of abstraction)HTML5 as a game console by Michal Budzynski It was an awesome session and blew my mind as how can you use HTML5 and CSS/JS to create games without any backend/server. One game was very cool where the code was around 5000 lines but only CSS no JS at all!Personal branding for developers by Susan Varty This was my favorite talk and I think most of the things I was able to relate about personal branding and how helpful as a professional developer it is to me. There is plenty of home-work I got for myself from this session and I am sure if any other developer like me look at this, will find some home-work for himself.

Experience at ConFoo

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

It was a wonderful journey to see innovations happening around various technology stacks and a beautiful trip to Montreal, Canada specially in winter (freezing at -5C to -10C).Confoo, 2012 had more than 100 speakers and there were more than 150 sessions in 3 days.Sessions I liked most (my favorite is last one):Continuous Delivery at Speed by Jospeh Wilk, where he talks about trade-offs between fast paced development Vs safe deployment. As a developer we like things to be deployed and released to users quickly and we use latest tools like Jenkins and for CI to deploy as soon as we commit a single line of code. So idea is to have a balance between speed and safety, i.e. zero failure builds and tools like guard can be very useful.How CMS architecture affects dev communities by Julian Egelstaff where he compared architecture of three CMS from PHP: TikiWiki, Xoops and Drupal and saw some patterns on how the communities around these CMS are reacting to the architecture. In a nutshell, "It doesn't seem to matter if you have lot of core developers, but it does matter that your community uses the architectural features of the core code as a foundation of their systems." Drupal has lot of flexibility as it has very smaller modules which can be plugged and play, while Xoops has "big module" architecure, which allows less flexibility and TikiWiki community is smaller, but the architecture is not modular and more or less like wiki way which makes it hard to extend.Make your project SOLID! by Tobias Schlitt It was very interesting to see how simply SOLID principles help in shaping your application.I am listing down only principals here as explanation would be a separate blog on this topic :)Single responsibility principleOpen/closed principleLiskov substitution principleInterface segregation principleDependency inversion principle (kind of principle of abstraction)HTML5 as a game console by Michal Budzynski It was an awesome session and blew my mind as how can you use HTML5 and CSS/JS to create games without any backend/server. One game was very cool where the code was around 5000 lines but only CSS no JS at all!Personal branding for developers by Susan Varty This was my favorite talk and I think most of the things I was able to relate about personal branding and how helpful as a professional developer it is to me. There is plenty of home-work I got for myself from this session and I am sure if any other developer like me look at this, will find some home-work for himself.

Tip of the day

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

On my current project I had to calculate date of Wednesday in nth week in mth year.Here is the trick:date-extension

Tip of the day

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

On my current project I had to calculate date of Wednesday in nth week in mth year.Here is the trick:date-extension

Rails upgrade from 3.0.7 to 3.1 and asset pipe-lining

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Following my previous blog, I happen to work on another rails upgrade at the beginning of my new project. This time rails 3.0.7 to 3.1. I though, I should document these steps, as it might help myself or someone else in future.I googled and found a good discussion on stack-overflow. As Forrest Ye gave the right answer, I began the migration step by step, as it is written:"Edit Gemfile, change Rails gem versiongem 'rails', '3.1.0'Also adds new gems introduced in 3.1.0group :assets do  gem 'sass-rails', "~> 3.1.0"  gem 'coffee-rails', "~> 3.1.0"  gem 'uglifier'endgem 'jquery-rails'runbundle update railsThen run rake rails:update and resolve conflicts."I found few conflicts and before accepting them, I tried to understand:1. config/application.rb: I paid attention to:config.assets.enabled = trueconfig.assets.version = '1.0' which means you are enabling assets pipe-lining  which is one of the feature of rails 3.1, I accepted the changes.2. config/environments/development.rb:config.action_view.debug_rjs = truewhich has been deprecated, so this line should be deleted, if you are using rjs in views, debugging is not supported now.config.assets.compress = falsewhich means assets compression is off in development, I accepted the changes.config.assets.debug = trueit means, you can see the assets being loaded in logs. I accepted this change.3. config/environments/production.rbI saw again configuration related to asset pipeline:config.assets.compress = trueconfig.assets.compile = falseconfig.assets.digest = trueSimply, accept these changes.Once this is done, move all assets from public/images, public/javascripts, public/stylesheets to app/assets/ directory. Again, you have to make sure, that youInclude css/javascript links in your layout file like this<%= stylesheet_link_tag "application" %><%= javascript_include_tag "application" %>Again, it is important to understand the behavior of asset pipeline and how it works. For example, in application.js file, you will have://= require_tree .that means, all the files from assets/javascripts directory will be loaded automatically, as application is being loaded, in hierarchical format. If you do need js files in sequence, mention that above this line, e.g.://= require jquery //= require jquery_ujs//= require highcharts//= require_tree .Similarly you have application.css file, which will load assets in hierarchy, so override it if needed. One important thing I noticed is about images, which are embedded in stylesheets. I had stylesheet.css as:/**= require_self*= require_tree .*/#header { height:20px; }body {background-image:url(../images/mainBack.png) !important; background-repeat:repeat-x;} So, after moving images to app/assets/images directory, I have to remove the relative path of the image:body {background-image:url(mainBack.png) !important; background-repeat:repeat-x;}Similarly for all other styles and that is it!

Rails upgrade from 3.0.7 to 3.1 and asset pipe-lining

over 5 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Following my previous blog, I happen to work on another rails upgrade at the beginning of my new project. This time rails 3.0.7 to 3.1. I though, I should document these steps, as it might help myself or someone else in future.I googled and found a good discussion on stack-overflow. As Forrest Ye gave the right answer, I began the migration step by step, as it is written:"Edit Gemfile, change Rails gem versiongem 'rails', '3.1.0'Also adds new gems introduced in 3.1.0group :assets do  gem 'sass-rails', "~> 3.1.0"  gem 'coffee-rails', "~> 3.1.0"  gem 'uglifier'endgem 'jquery-rails'runbundle update railsThen run rake rails:update and resolve conflicts."I found few conflicts and before accepting them, I tried to understand:1. config/application.rb: I paid attention to:config.assets.enabled = trueconfig.assets.version = '1.0' which means you are enabling assets pipe-lining  which is one of the feature of rails 3.1, I accepted the changes.2. config/environments/development.rb:config.action_view.debug_rjs = truewhich has been deprecated, so this line should be deleted, if you are using rjs in views, debugging is not supported now.config.assets.compress = falsewhich means assets compression is off in development, I accepted the changes.config.assets.debug = trueit means, you can see the assets being loaded in logs. I accepted this change.3. config/environments/production.rbI saw again configuration related to asset pipeline:config.assets.compress = trueconfig.assets.compile = falseconfig.assets.digest = trueSimply, accept these changes.Once this is done, move all assets from public/images, public/javascripts, public/stylesheets to app/assets/ directory. Again, you have to make sure, that youInclude css/javascript links in your layout file like this<%= stylesheet_link_tag "application" %><%= javascript_include_tag "application" %>Again, it is important to understand the behavior of asset pipeline and how it works. For example, in application.js file, you will have://= require_tree .that means, all the files from assets/javascripts directory will be loaded automatically, as application is being loaded, in hierarchical format. If you do need js files in sequence, mention that above this line, e.g.://= require jquery //= require jquery_ujs//= require highcharts//= require_tree .Similarly you have application.css file, which will load assets in hierarchy, so override it if needed. One important thing I noticed is about images, which are embedded in stylesheets. I had stylesheet.css as:/**= require_self*= require_tree .*/#header { height:20px; }body {background-image:url(../images/mainBack.png) !important; background-repeat:repeat-x;} So, after moving images to app/assets/images directory, I have to remove the relative path of the image:body {background-image:url(mainBack.png) !important; background-repeat:repeat-x;}Similarly for all other styles and that is it!

Rails upgrade from 2.3.5 to 3.0.9

about 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Few weeks back I did rails upgrade for my current project from rails 2.3.5 to rails 3.0.9 (on Windows 7).I began with rails 3 upgrade guide. So, first step was to install ruby 187, which I already had on my system with pikThere is a good series on rails on upgrading to rails 3 from Ryan Bates:http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-1http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-2http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-3Some how the rails-upgrade-plugin did not work for me (as I was working on Windows 7) .I then followed the-path-to-rails-3-approaching-the-upgrade step-by-step and I got application 80% upgraded, the rest 20% was a tough part.In this blog, I am writing about challenges I faced in this process.Installing rails 3.0.9 gem:Somehow gem install rails shown errors:C:\myapp>gem install railsSuccessfully installed rails-3.0.91 gem installedInstalling ri documentation for rails-3.0.9...file 'lib' not foundInstalling RDoc documentation for rails-3.0.9...file 'lib' not foundI used,C:\myapp>gem install rails --no-rdoc --no-riSuccessfully installed rails-3.0.91 gem installedroutes.rbI had to update the routes.rb file and I found one really helpful link: http://stackoverflow.com/questions/3103765/routing-in-rails-3-map-with-optionsDeprecation warning for cookie_store:DEPRECATION WARNING: ActionController::Base.session= is deprecated. Please configure it on your application with config.session_store :cookie_store, :key => '....'. (called from C:/myapp/config/initializers/session_store.rb:7)So, I did:module Myapp   class Application < Rails::Application     config.session_store :cookie_store, :key => '_myapp_session', :secret => 'some-secret-string-very-long' Also, I removed C:/myapp/config/initializers/session_store.rb file.Reference: http://stackoverflow.com/questions/3720379/sqlsessionstore-in-rails-3 and http://apidock.com/rails/ActiveRecord/SessionStoreLogging the deprecation warningsI saw another warning:You did not specify how you would like Rails to report deprecation notices for your development environment, please set config.active_support.deprecation to :log at config/environments/development.rbSo, I updated development.rb (and other .rb files):Myapp::Application.configure do    config.active_support.deprecation = :log consider_all_requests_local warningDEPRECATION WARNING: ActionController::Base.consider_all_requests_local= is deprecated. Please configure it on your application with config.consider_all_requests_local=.So, I added this snippet in config/environments/development.rbMyapp::Application.configure do config.consider_all_requests_local = trueSome easy once1. DEPRECATION WARNING: RAILS_ENV is deprecated. Please use ::Rails.env.So, wherever I was using RAILS_ENV, I replaced with Rails.env2. DEPRECATION WARNING: RAILS_ROOT is deprecated. Please use ::Rails.root.to_s.So, wherever I was using RAILS_ROOT, I replaced with Rails.root.to_sActionMailer warnings1. When you need to set character set for action mailer, you specify in initializer.rb, which throws this warning:DEPRECATION WARNING: ActionMailer::Base.default_charset=value is deprecated, use default :charset => value insteadI passed hash to the default method in application.rb:Myapp::Application.configure do default :charset => 'utf-8'2 Similarly the mime version we set in initializers:DEPRECATION WARNING: ActionMailer::Base.default_mime_version=value is deprecated, use default :mime_version => value instead.I passed hash to the default method in application.rb:Myapp::Application.configure do default :mime_version => '1.0'3. For multipart emails the setting has to be adjusted:DEPRECATION WARNING: ActionMailer::Base.default_implicit_parts_order=value is deprecated, use default :implicit_parts_order => value insteadThis is again can be passed to default method:Myapp::Application.configure do   default :parts_order => [ "text/plain", "text/enriched", "text/html" ]html_safe in view?For 2-3 hours I struggled to find the reason, why the select tag was not producing the tags. When I found it I understand that this is again a security addition to convert strings into html safe form. So, all your '&lt;' will be converted to '<' and all '&gt;' will be converted into '>'. I actually added .html_safe at the end of each string in view and that showed all the tags finally.Reference: rails-3-select-tag-not-producing-dom-elementsRemoved config.action_view.cache_template_loading, use config.cache_classes insteadReference: https://github.com/rails/rails/commit/83e29b9773ac113ceacb1e36c2f333d692de2573RspecI was using rspec and here is the deprecation warning I got:*****************************************************************DEPRECATION WARNING: you are using a deprecated constant that will be removed from a future version of RSpec.C:/cit/spec/controllers/activity_logs_controller_spec.rb:1:in `require'* Spec is deprecated.* RSpec is the new top-level module in RSpec-2******************************************************************************************************************************DEPRECATION WARNING: you are using deprecated behaviour that will be removed from a future version of RSpec.C:/cit/spec/spec_helper.rb:17* Spec::Runner.configure is deprecated.* please use RSpec.configure instead.So, I have to use rspec-rails-2 which supports rails 3.Reference: http://groups.google.com/group/cukes/browse_thread/thread/40c4c2aea1c07afe/cb63eb7f0b733646?lnk=raotAjax stopped workingI was using jQuery as javascript library, and I found somehow the ajax calls stopped working after the upgrade. I later found that there is a security threat and a fix for that is availableHere is what I had to do:Step#1. In application.html.erb, I had to include csrf_meta_tag:<%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> Step#2. I added this snippet to application.js:$(document).ajaxSend(function(e, xhr, options) {   var token = $("meta[name='csrf-token']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token); }); Reference: csrf-protection-bypass-in-ruby-on-railsRackBaseURI instead of RailsBaseURII was using RailsBaseURI in apache, but after upgrade to Rails 3, I had to update it to RackBaseURIReference: RackBaseURILast but not least, I was using valid? method in helper to check if the object is valid or not and based on that I was displaying certain fields, which was working fine in Rails 2.  In Rails 3 valid? method will trigger validations as well, which caused field_with_errors div to show-up all the time (even when the validation should not happen). I changed the logic to not use valid? method to display other fields and it solved the problem.

Rails upgrade from 2.3.5 to 3.0.9

about 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

Few weeks back I did rails upgrade for my current project from rails 2.3.5 to rails 3.0.9 (on Windows 7).I began with rails 3 upgrade guide. So, first step was to install ruby 187, which I already had on my system with pikThere is a good series on rails on upgrading to rails 3 from Ryan Bates:http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-1http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-2http://asciicasts.com/episodes/226-upgrading-to-rails-3-part-3Some how the rails-upgrade-plugin did not work for me (as I was working on Windows 7) .I then followed the-path-to-rails-3-approaching-the-upgrade step-by-step and I got application 80% upgraded, the rest 20% was a tough part.In this blog, I am writing about challenges I faced in this process.Installing rails 3.0.9 gem:Somehow gem install rails shown errors:C:\myapp>gem install railsSuccessfully installed rails-3.0.91 gem installedInstalling ri documentation for rails-3.0.9...file 'lib' not foundInstalling RDoc documentation for rails-3.0.9...file 'lib' not foundI used,C:\myapp>gem install rails --no-rdoc --no-riSuccessfully installed rails-3.0.91 gem installedroutes.rbI had to update the routes.rb file and I found one really helpful link: http://stackoverflow.com/questions/3103765/routing-in-rails-3-map-with-optionsDeprecation warning for cookie_store:DEPRECATION WARNING: ActionController::Base.session= is deprecated. Please configure it on your application with config.session_store :cookie_store, :key => '....'. (called from C:/myapp/config/initializers/session_store.rb:7)So, I did:module Myapp   class Application < Rails::Application     config.session_store :cookie_store, :key => '_myapp_session', :secret => 'some-secret-string-very-long' Also, I removed C:/myapp/config/initializers/session_store.rb file.Reference: http://stackoverflow.com/questions/3720379/sqlsessionstore-in-rails-3 and http://apidock.com/rails/ActiveRecord/SessionStoreLogging the deprecation warningsI saw another warning:You did not specify how you would like Rails to report deprecation notices for your development environment, please set config.active_support.deprecation to :log at config/environments/development.rbSo, I updated development.rb (and other .rb files):Myapp::Application.configure do    config.active_support.deprecation = :log consider_all_requests_local warningDEPRECATION WARNING: ActionController::Base.consider_all_requests_local= is deprecated. Please configure it on your application with config.consider_all_requests_local=.So, I added this snippet in config/environments/development.rbMyapp::Application.configure do config.consider_all_requests_local = trueSome easy once1. DEPRECATION WARNING: RAILS_ENV is deprecated. Please use ::Rails.env.So, wherever I was using RAILS_ENV, I replaced with Rails.env2. DEPRECATION WARNING: RAILS_ROOT is deprecated. Please use ::Rails.root.to_s.So, wherever I was using RAILS_ROOT, I replaced with Rails.root.to_sActionMailer warnings1. When you need to set character set for action mailer, you specify in initializer.rb, which throws this warning:DEPRECATION WARNING: ActionMailer::Base.default_charset=value is deprecated, use default :charset => value insteadI passed hash to the default method in application.rb:Myapp::Application.configure do default :charset => 'utf-8'2 Similarly the mime version we set in initializers:DEPRECATION WARNING: ActionMailer::Base.default_mime_version=value is deprecated, use default :mime_version => value instead.I passed hash to the default method in application.rb:Myapp::Application.configure do default :mime_version => '1.0'3. For multipart emails the setting has to be adjusted:DEPRECATION WARNING: ActionMailer::Base.default_implicit_parts_order=value is deprecated, use default :implicit_parts_order => value insteadThis is again can be passed to default method:Myapp::Application.configure do   default :parts_order => [ "text/plain", "text/enriched", "text/html" ]html_safe in view?For 2-3 hours I struggled to find the reason, why the select tag was not producing the tags. When I found it I understand that this is again a security addition to convert strings into html safe form. So, all your '&lt;' will be converted to '<' and all '&gt;' will be converted into '>'. I actually added .html_safe at the end of each string in view and that showed all the tags finally.Reference: rails-3-select-tag-not-producing-dom-elementsRemoved config.action_view.cache_template_loading, use config.cache_classes insteadReference: https://github.com/rails/rails/commit/83e29b9773ac113ceacb1e36c2f333d692de2573RspecI was using rspec and here is the deprecation warning I got:*****************************************************************DEPRECATION WARNING: you are using a deprecated constant that will be removed from a future version of RSpec.C:/cit/spec/controllers/activity_logs_controller_spec.rb:1:in `require'* Spec is deprecated.* RSpec is the new top-level module in RSpec-2******************************************************************************************************************************DEPRECATION WARNING: you are using deprecated behaviour that will be removed from a future version of RSpec.C:/cit/spec/spec_helper.rb:17* Spec::Runner.configure is deprecated.* please use RSpec.configure instead.So, I have to use rspec-rails-2 which supports rails 3.Reference: http://groups.google.com/group/cukes/browse_thread/thread/40c4c2aea1c07afe/cb63eb7f0b733646?lnk=raotAjax stopped workingI was using jQuery as javascript library, and I found somehow the ajax calls stopped working after the upgrade. I later found that there is a security threat and a fix for that is availableHere is what I had to do:Step#1. In application.html.erb, I had to include csrf_meta_tag:<%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> Step#2. I added this snippet to application.js:$(document).ajaxSend(function(e, xhr, options) {   var token = $("meta[name='csrf-token']").attr("content"); xhr.setRequestHeader("X-CSRF-Token", token); }); Reference: csrf-protection-bypass-in-ruby-on-railsRackBaseURI instead of RailsBaseURII was using RailsBaseURI in apache, but after upgrade to Rails 3, I had to update it to RackBaseURIReference: RackBaseURILast but not least, I was using valid? method in helper to check if the object is valid or not and based on that I was displaying certain fields, which was working fine in Rails 2.  In Rails 3 valid? method will trigger validations as well, which caused field_with_errors div to show-up all the time (even when the validation should not happen). I changed the logic to not use valid? method to display other fields and it solved the problem.

development on Windows deploying to Linux with cruise and bundler?

over 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

In my previous post, I set-up bundler with rails-2.2.2 application. Soon after that, I found myself in another trouble.When I set-up bundler, I had to create Gemfile for the gems required by my rails application. Also, when I run bundle install command, it creates Gemfile.lock file, this file holds various information:Gem repositories (sources)Which version of gem the application is using (gem specification)If there is any dependency of any gem, then what they arePlatform detailsIn my current project, I use Windows 7 as development machine, there is a cruise server on linux machine, I am committing my code to a subversion repository and once the build passes on cruise it deploys to a linux server. Every time I run bundle install, it creates a Gemfile.lock with windows version of gems and platform details for windows. If I commit Gemfile and Gemfile.lock, it fails the build and I have to manually login to cruise box and remove those files and re-run bundle install command, so that it generates the Gemfile and Gemfile.lock for linux environment, so that on integration and production servers, the Gemfile and Gemfile.lock will remain with linux version and there is no failures there. This was a pain.I wrote a ruby script to do this job for me. With this script, I removed everything windows specific in Gemfile and Gemfile.lock I can think of. Here is what I did (look at: https://github.com/gouravtiwari/windows_linux_fix_for_bundler for source code)I extended cruise:init rake task(created fix.rake in lib), to include my ruby script.In the script, I am removing windows traces, updating the platform details, running bundle command and then committing the latest Gemfile and Gemgfile.lock toSVN.This way, if by mistake I am committing Gemfile and Gemfile.lock to SVN, I don't need to go to cruise and re-generate Gemfile and Gemfile.lock.

development on Windows deploying to Linux with cruise and bundler?

over 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

In my previous post, I set-up bundler with rails-2.2.2 application. Soon after that, I found myself in another trouble.When I set-up bundler, I had to create Gemfile for the gems required by my rails application. Also, when I run bundle install command, it creates Gemfile.lock file, this file holds various information:Gem repositories (sources)Which version of gem the application is using (gem specification)If there is any dependency of any gem, then what they arePlatform detailsIn my current project, I use Windows 7 as development machine, there is a cruise server on linux machine, I am committing my code to a subversion repository and once the build passes on cruise it deploys to a linux server. Every time I run bundle install, it creates a Gemfile.lock with windows version of gems and platform details for windows. If I commit Gemfile and Gemfile.lock, it fails the build and I have to manually login to cruise box and remove those files and re-run bundle install command, so that it generates the Gemfile and Gemfile.lock for linux environment, so that on integration and production servers, the Gemfile and Gemfile.lock will remain with linux version and there is no failures there. This was a pain.I wrote a ruby script to do this job for me. With this script, I removed everything windows specific in Gemfile and Gemfile.lock I can think of. Here is what I did (look at: https://github.com/gouravtiwari/windows_linux_fix_for_bundler for source code)I extended cruise:init rake task(created fix.rake in lib), to include my ruby script.In the script, I am removing windows traces, updating the platform details, running bundle command and then committing the latest Gemfile and Gemgfile.lock toSVN.This way, if by mistake I am committing Gemfile and Gemfile.lock to SVN, I don't need to go to cruise and re-generate Gemfile and Gemfile.lock.

Bundler with rails-2.2.2

over 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

I am working on a rails application, which is on rails-2.2.2. I have used bundler on rails-3 application, but never tried bundler for rails-2.2.2. The benefit of bundler is huge, it is gem manager for rails application. So, now no pain of vendoring/localizing gems in rails application.gembundler.com gives step-by-step process on how to install/configure bundler for rails-2.3.x and rails-3.x applications. So, I wanted to find out how does it work with rails-2.2.2 application.So, here is how I did.First of all I have installed bundlergem install bundler // installed bundler 1.0.10Updated rubygemsgem update --system // rubygems > 1.3.6Created config/preinitializer.rb file with below content:begin  require "rubygems"  require "bundler"rescue LoadError  raise "Could not load the bundler gem. Install it with `gem install bundler`."endif Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24")  raise RuntimeError, "Your bundler version is too old for Rails 2.3." +   "Run `gem install bundler` to upgrade."endbegin  # Set up load paths for all bundled gems  ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)  Bundler.setuprescue Bundler::GemNotFound  raise RuntimeError, "Bundler couldn't find some gems." +    "Did you run `bundle install`?"end Created Gemfile with something similar:require 'rubygems'source 'http://rubygems.org'source 'http://gemcutter.org'source 'http://gems.github.com'gem 'rails', '2.2.2'gem 'hpricot', '0.6.0'gem "composite_primary_keys", '1.0.8'gem 'javan-whenever', '0.3.7'gem 'mysql', '2.8.1'gem 'activerecord-oracle_enhanced-adapter', '1.1.9'gem 'ruby-oci8', '1.0.3'group :test do  gem 'mocha', '0.9.5'  gem 'rspec',             '1.3.1', :require => 'spec'  gem 'rspec-rails',       '1.3.3'  gem 'database_cleaner',  '0.5.0'  gem 'capybara'  gem 'ruby-debug'  gem 'factory_girl'endFrom the application root, I ran:bundle installThat is it and I have my application up and running with bundler. Once I tested my application, I removed gems folder from /vendor (no need for localized version of gems now.)

Bundler with rails-2.2.2

over 6 years ago | Gourav Tiwari: easy_software = Agile.find(ruby_on_rails)

I am working on a rails application, which is on rails-2.2.2. I have used bundler on rails-3 application, but never tried bundler for rails-2.2.2. The benefit of bundler is huge, it is gem manager for rails application. So, now no pain of vendoring/localizing gems in rails application.gembundler.com gives step-by-step process on how to install/configure bundler for rails-2.3.x and rails-3.x applications. So, I wanted to find out how does it work with rails-2.2.2 application.So, here is how I did.First of all I have installed bundlergem install bundler // installed bundler 1.0.10Updated rubygemsgem update --system // rubygems > 1.3.6Created config/preinitializer.rb file with below content:begin  require "rubygems"  require "bundler"rescue LoadError  raise "Could not load the bundler gem. Install it with `gem install bundler`."endif Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.24")  raise RuntimeError, "Your bundler version is too old for Rails 2.3." +   "Run `gem install bundler` to upgrade."endbegin  # Set up load paths for all bundled gems  ENV["BUNDLE_GEMFILE"] = File.expand_path("../../Gemfile", __FILE__)  Bundler.setuprescue Bundler::GemNotFound  raise RuntimeError, "Bundler couldn't find some gems." +    "Did you run `bundle install`?"end Created Gemfile with something similar:require 'rubygems'source 'http://rubygems.org'source 'http://gemcutter.org'source 'http://gems.github.com'gem 'rails', '2.2.2'gem 'hpricot', '0.6.0'gem "composite_primary_keys", '1.0.8'gem 'javan-whenever', '0.3.7'gem 'mysql', '2.8.1'gem 'activerecord-oracle_enhanced-adapter', '1.1.9'gem 'ruby-oci8', '1.0.3'group :test do  gem 'mocha', '0.9.5'  gem 'rspec',             '1.3.1', :require => 'spec'  gem 'rspec-rails',       '1.3.3'  gem 'database_cleaner',  '0.5.0'  gem 'capybara'  gem 'ruby-debug'  gem 'factory_girl'endFrom the application root, I ran:bundle installThat is it and I have my application up and running with bundler. Once I tested my application, I removed gems folder from /vendor (no need for localized version of gems now.)