Writing a rake task in rails i pretty simple.In this post i will describe creating a rake task to reset the password of every user on the system.Maybe you had a breach and to prevent identity theft you reset the users password and send it to the user through his email address.

To create a rake task we firstly have to namespace it so that it doesnt conflict with existing rake tasks and it also helps us keep our code more modularized.

/// lib/tasks/defcon.rake
require 'securerandom'
namespace :defcon do
  desc 'Reset users emails'
  task :got_hacked do
    begin
      User.all.each do |user|
        password = SecureRandom.hex.slice(0,10)
        user.password = password
        user.save
        UserMailer.reset_password(user,password)
      end
    rescue Exception => e
      puts "#{e.message} occured"
    end
  end
end

We first require the securerandom library.This is required to generate some random password for each user.
We namespace the task with a name,for now i have called defcon.
The task name here is got_hacked which runs once the we type rake defcon.got_hacked so if in case we get hacked we can instantly reset the password for all the users in our system.
Inside the task we have begin and rescue block,this is make sure that we catch any exception that occurs and output it on the screen.
So the regular flow of the program is as such.We loop through all the users in the system (assuming there is a user model).We generate a random password and set that as the password for the current user in the loop.We save the password in the database and then send them a email stating that their password has been reset.
The UserMailer class for sending the email is given below

/// app/mailer/user_mailer.rb
class UserMailer < ActionMailer::Base
  def reset_password(user,password)
    mail(to: user.email, subject: "We got hacked", from: "xxx@xxxx.com")
  end
end

The view for the email

/// app/view/user_mailer/reset_password.html.erb
Dear <%= user.name %>,
We have been hacked.Here is you new password for the account.
password : <%= user.password %>



If you are planning to scale your website to accommodate for extra traffic on the website.You have two options you can scale vertically or horizontally.
Vertical scaling usually involves adding extra ram/processing power which may be desired,but there is a limit to this kind of scaling.
Horizontal scaling is were you setup multiple machines and they work together to get the work done.Haproxy is loadbalancer which will let you scale your infrastructure horizontally.

To setup loadbalancing between 2 machines is pretty simple.Firstly you will require two machines with static address or a DNS entry to identify the machines.

I will using vagrant during this process of setting up a loadbalancer.I will be using vagrant a virtual machine environment which does have a gui.More information about it can be found at http://vagrantup.com/.

I have setup up virtual machines running ubuntu 13.04 LTS.Both the machines are running Apache2 with default settings.You can replicate the same by running this on the terminal.

sudo apt-get update
sudo apt-get install apache2 php5
sudo apt-get install libapache2-mod-php5
sudo service apache2 restart

Next we get the ip address of the two machines and store them someplace safely.

ifconfig eth0

The ip address of machine one is 10.0.2.2 and the second machine is 10.0.2.3.

We them launch another vm with haproxy.

Run sudo apt-get install haproxy

This will install haproxy with default settings.
Next to start haproxy as service we have to enable it in the configuration file.

vi /etc/default/haproxy
ENABLED=1
sudo service haproxy restart

Next we haproxy to point to the two servers we setup earlier.Next we move the original configuration of haproxy and keep it as a backup.

sudo mv /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.bak

We then create our own configuration file with

sudo vi /etc/haproxy/haproxy.cfg

Add this to the cfg file.

global
    log 127.0.0.1 local0 notice
    maxconn 2000
    user haproxy
    group haproxy

listen appname 0.0.0.0:80
    mode http
    stats enable
    cookie SRVNAME insert
    balance roundrobin
    option httpclose
    option forwardfor
    server server1 10.0.2.2:80 check
    server server1 10.0.2.3:80 check

Once this is done a quick restart of haproxy and the haproxy acts as the frontend for the incoming traffic.



When every you include underscore into your code,it does a certain number of checks to make sure that there is no conflict and dependency issues.It also does a check and setup of the parameters that are required to use underscore.

  var root = this;
  var previousUnderscore = root._;
  var breaker = {};
  var ArrayProto = Array.prototype, ObjectProto = Object.prototype, FuncProto = Function.prototype;

  var 
    push = ArrayProto.push,
    slice = ArrayProto.slice,
    concat = ArrayProto.concat,
    toString = ObjectProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  _.VERSION = '1.5.2';
var root = this;

Underscore sets root as this ie it sets the root as the windows of the javascript context.

var previousUnderscore = root._;

We save the previous underscore in previousUnderscore.

var breaker = {};

Creates an empty object used later to break out out a loop.

var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

Creates an empty Array object and function to work on later.

 var
    push             = ArrayProto.push,
    slice            = ArrayProto.slice,
    concat           = ArrayProto.concat,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

Create references for the function so that we dont have to recreate one every time we have to use it.

var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

Create references for the native Ecmascript 5 implementation.

var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

Create a variable _ function.if underscore is already loaded we return it.If _ is not the same as the one loaded.we return a new instance of underscore.

Required to use underscore with node.js.

_.VERSION = '1.5.2'

Sets the version of underscore.



Underscore is a set of utility functions written in underscore.With more than 80 different functions to make our lives easier.Its time to dissect them and understand how they work.

Underscore includes some setup code along with the functions below in the raw source of the library.The rest of the 80+ functions are mentioned below:

Underscore SetupĀ 

  1. Each method
  2. Map method
  3. Reduce method
  4. ReduceRight method
  5. Find method
  6. Filter method
  7. Reject method
  8. Every method
  9. Any method
  10. Contains method
  11. Invoke method
  12. Pluck method
  13. Where method
  14. FindWhere method
  15. Max method
  16. Min method
  17. Shuffle method
  18. Sample method
  19. SortBy method
  20. GroupBy method
  21. IndexBy method
  22. Countby method
  23. SortedIndex method
  24. ToArray method
  25. Size method
  26. First method
  27. Initial method
  28. Last method
  29. Rest method
  30. Compact method
  31. Flatten method
  32. Without method
  33. Uniq method
  34. Union method
  35. Intersection method
  36. Difference method
  37. Zip method
  38. Object method
  39. IndexOf method
  40. LastIndexOf method
  41. Range method
  42. Bind method
  43. Partial method
  44. BindAll method
  45. Memoize method
  46. Delay method
  47. Defer method
  48. Throttle method
  49. Debounce method
  50. Once method
  51. Wrap method
  52. Compose method
  53. After method
  54. Keys method
  55. Values method
  56. Pairs method
  57. Invert method
  58. Functions method
  59. Extend method
  60. Omit method
  61. Defaults method
  62. Clone method
  63. Tap method
  64. Isequal method
  65. isempty method
  66. isElement method
  67. isArray method
  68. isObject method
  69. isFinite method
  70. isNaN method
  71. isBoolean method
  72. isNull method
  73. isUndefined method
  74. has method
  75. isFinite method
  76. identity method
  77. times method
  78. random method
  79. result method
  80. mixin method
  81. template method
  82. chain method



After destroying my previous blog(thanks to ec2).I have planned to take regular backups of my blog.Making sure I have a hot as well as soft backup,everything from the theme i developed to the content on the page.

Steps I have taken to prevent such a mishap.

  • Version Control – I am starting to version control the theme I will use on the site .
  • Remote repository – Having a remote repository is useful as it works as a backup with the added benefit of working remotely.I am using Bitbucket (link) which allows me to have unlimited private repositories and it is completely free.
  • The server deployment itself is version control as I have installed it with chef(link).
  • Lastly I have installed Backwpup which is a free plugin for wordpress.I does automatic backup of the data similar to a cron job.It lets you make a complete backup of you database as well as the wp-content folder of the website.