When writing ruby programs we usually write decorators to extend the methods of a particular object.Using them as form objects is one of the most common uses of a decorator.Ruby makes it simple and easy to create a decorator for a ruby object.

class StuffDecorator
  def initialize(og)
    @og = og
  end
  def stuff
    @og.class
  end
end

Now we can call the stuff method and it will easily return the class of the original object.

While working on an API backend I came across roar.Its a ruby library that allows you to add methods to your ruby object without breaking a sweat.

Here’s an example from the docs

require 'roar/decorator'
class Song
  include ActiveModel::Model
  attr_accessor :title
end

class SongRepresenter < Roar::Decorator
  include Roar::JSON

  property :title
end

song = Song.new(title: "Medicine Balls")

SongRepresenter.new(song).to_json #=> {"title":"Medicine Balls"}

As you can see the property method calls the original object and returns the response.The best part is now you can get the json serialized version of the object.

If you want to add a custom method you can easily add a method or even override and existing one.

class SongRepresenter < Roar::Decorator
  include Roar::JSON

  def more
    represented.title
  end
  property :title
  property :more, exec_context: :decorator
end

To make things better Roar allows you to serialize your decorator to JSON-API, XML, or even HAL.

All you have to do is include it in the decorator

class SongRepresenter < Roar::Decorator
  include Roar::JSON
  include Roar::XML

  property :title
end

song = Song.new(title: "Medicine Balls")

SongRepresenter.new(song).to_xml #=> "\n  test\n" 

 



Whenever we think about integrating sms in our application, the only company that comes to comes to is twilio. Twilio is a really good service however they are relatively expensive to their competitors especially if you know where your target audience is from.

In my case I was working for startup in Spain which operated in the Spain/Portugal region.For a while we were using twilio, but soon the number of sms we were sending grow to huge amount and we were spending a significant amount of money on it.

We came across another provider smsgateway.to .Compared to Twilio it wasnt a very popular provider but its pricing was much better.We gave this a provider a try and tested sending SMS through them.Their delivery rate was pretty high and we decided to switch to them.We came across another issue, they didnt have a ruby client so I wrote a quick one and was ready to use it production.

We are now using the service in production for 2 months and we have had no issue so far.More over we reduced the cost of our sms by more than 3 times.

The library is available at https://github.com/h0lyalg0rithm/sms_gateway_to



In my quest to move away from heroku. I came across Capistrano a popular automated deployment tool written in Ruby. Capistrano is really popular with millions of downloads and lots of Plugins

Here is how I setup Capistrano to deploy static websites and create rollbacks in case the build was buggy.

Capistrano deploys the code to /var/www/application_name.It does so by logging in the user into the server and pulling the repo from the git repo specified.On top of this capistrano adds a bunch of commands to make this process simpler.

Running

cap -T

 

shows the lists of commands capistrano supports.



Devise is such a beautiful library.I don’t see any reason to write my own authentication component on rails.Moreover Devise allows you to custom every single feature of the library.

Last week I was tasked with creating a registration page for a startup, to make the sign up process simpler we would allow the user to create a company in the same form.Devise made this task very simple.By default devise creates routes for user sign up,but this route would conflict if you have a user resource route.Here is how you can customize the url to use the right controller and route url.
The path_names property sets the registration url to ‘/users/register’ and since we want to create the company relation we use a custom registration controller.
The registration controller’s new method overrides the Devise::RegistrationController.

build_resource({}) and set_minimum_password_length enforces the minimum password length and also creates the resource which in this case is the user.
We also create a model for the company.

The method create on the other hand just takes the params and generates a user model from it.

The method sign_up_params is overridden to allow the company attributes to be used as rails model attributes More info.

The view on the other hand is also simple.Just add the relations and devise takes care of the rest.

As you can see the company form field is generated similarly to rails form.



Yesterday I came across this nifty tool to update the version numbers in my Gemfile.

Gemfly

Now you might be wondering why not just use the bundler to take care of stuff.The problem with bundler is firstly its slow and whenever there are transient dependencies it would tell us to update the dependency rather than taking care of it.

Take a look at it Gemfly



Postgres is a really powerful database with a lot of features, One of the most important features which is very rarely found in other databases is “Table inheritance”

Table inheritance is very similar to class inheritance of OOP.In Table inheritance you have a parent table which is inherited by another table with extra columns in it.

By default the pg gem doesnt support table inheritance.

In the current project that I am working on, the business logic required the user to have template using which he could create items.This is where table inheritance shines.It allowed me to create the template model which contained all the generic attributes for the item.So everytime I would update the template the relevant model for the template would also be updated.
Continue reading



Automated testing an application can be difficult and time consume.Even after writing your tests you will always have to run it again and again to achieve the red green refactor flow.

To make this task easier the ruby ecosystem has a really powerful and versatile test runner called Guard.

Guard run like a daemon on your machine and runs tests whenever your code changes.This helps you maintain concentration and focus on the tests and code rather than monotonous manual running of the test.
Continue reading



Today I am write about a gem that I released a couple of days ago.The gem allows you to integrate the clockwork gem with Capistrano.
Capistrano is a really powerful tool to automate deployment and perform tasks during or after the deployment.

Clockwork is the cron job of Ruby world.Compared to the whenever gem (another cron gem) clockwork much more expressive and its looks very rubyish.

I looked around for a a plugin for Capistrano which would help me restart clockwork whenever I would deploy.

Using Capistrano-clockwork is very straightforward, like most the Capistrano plugins,it only supports capistrano 3 and above.
All you have to do it mention Capistrano-clockwork in your gemfile and add ‘capistrano/clockwork’

That’s it.from now onwards whenever you deploy the gem restarts clockwork

If you don’t want the clockwork daemon to restart ,you can disable it by setting clockwork_default_hooks to false

set :clockwork_default_hooks, false

Moreover you can perform other tasks via the following commands:

cap clockwork:start
cap clockwork:restart
cap clockwork:status
cap clockwork:stop



In Ruby 2.0 we were first introduced to keyword arguments.Keyword Arguments are really useful and they clean up the redundant code.

Pre 2.0

def get _stuff(options={})
    first = options.fetch(:first)
    last = options.fetch(:last)
end

Now

def get_stuff(last:'last',first:'first')
end

So now we dont need to fetch arguments out of a hash we can just pass it along to the function and it becomes available as arguments.

But with comes at a cost.If you want to specify optional arguments this breaks really easily.Lets take this example.We have a method with two keyword arguments and we want to override the first argument

def get_stuff(first:"first",last:'last')
end

get_stuff("really_first")
#ArgumentError: wrong number of arguments (1 for 0)

We get this error because the method expects there to be a key value in the arguments of the method.Moreover ruby spits out its regular ArgumentError wrong number of arguments(1 for 0).

Currently there is not go way to avoid this sort of issue.Nevertheless keyword arguments offer more flexibility and structure to the code.We can also mix together a hash and keyword argument.

def ff(test:1,more:10)
   "#{test} #{more}"
end

hash = { test: 2, more: 1000}

ff hash # => "2 1000"

This code works well until the hash keys are the same as the keyword argument

hash = { test: 2, more: 1000, extra: 1}

ff hash # => ArgumentError: unknown keyword: extra

Again there is no good way around this apart from cleaning up the arguments before you pass it to the function



Everywhere you go either to eat, sleep and even fly.You will always come across open wireless networks.

Currently where I reside most of the shopping malls have free to use Internet.In exchange for your traffic and mobile number you get to access the Internets at crawling speed.These networks are usually open networks, so basically your traffic is naked and unencrypted.Any one can sniff the traffic,inject traffic into your stream and even MITM you, So rather than staying vulnerable target just use a VPN.You have two options to get a VPN,either you buy a VPN from a VPN provider which you cannot certainly cannot trust for anonymity OR the better option setup your own VPN.

Last week I finished my VPN cookbook and this post is a follow up to my previous rant about documentation and how value of open source is diminished without good documentation.

Let’s get to the meat of the post,the post will help you setup your own VPN server ,so you no longer have to worry about open networks.

  • First you need to get chef installed.Download it from here.
  • Then install two ruby gems to help you install the VPN server.
    Librarian-chef a ruby gem to manage your chef repositories.
    Knife-solo is like a tool which understand the chef cookbooks and helps you run the code on your server

Once you have the prerequisites installed, create a Cheffile and add my cookbook to it.Your cheffile should look like this.

cookbook 'pptpd', github: 'h0lyalg0rithm/pptpd'

Then run librarian install to download all the cookbooks to your computer.

Then run knife solo [email protected] and this will run the chef client on your server and install the recipes.

Once you run it you will notice that it creates a mode directory which will contain a json file.
Edit you json file to add the username and password you want setup in your VPN server.

{
  "run_list": [
    "recipe[pptpd]"
  ],
  "automatic": {
    "ipaddress": "host"
  },
  "pptpd":{
    "users":[{
        "username": "user",
        "password": "password"
      }]
  }
}

Now you have the VPN setup connect to it.PPTPD is one of the oldest VPN servers out there.It should even work on older smart phones even some of the old nokias.