babinho's weblog

Ruby and Coffee

What I Have Learned From a Hackathon

| Comments

I’ve attended a hackathon yesterday, that was the first “real” one in my life, and i’m still a bit under the influence. It was organised by the great people from Osijek Software City, and i thank them so much for the experience. I’ve learned so much, and almost nothing technical, because hackathons aren’t about it, as you will find out.

The topic: Crowd funding application

The topic was to make a simple crowd funding application. Nothing really complex, just a basic feature list with points for each complete feature.

The implementation: Rails

We chose Ruby on Rails as our implementation platform. That was a great choice, as we know it so well, and it would show later, that rails was the best framework for the rapid prototyping needed to win the hackathon. The only thing lacking, where we lost a lot of points, was the front-end design, but you can’t expect a team of 3 backend developers and one software tester to create something really pretty. Although our UX was great, as we were using bootstrap, and not really in a great way.

The mistakes…

Overthinking it

We had a feature list to complete, which is fairly easy to do with rails, but we managed not to complete every functionality, just because we were loosing time hacking on the front-end to make it look acceptable.

Making it too complex

In a hackathon, time is working against you, you can say the same in product work, as unlimited time time is a thing no one has. You have to make your features concise, and make them do only the stuff that needs to be done.

The learning…

KISS

Keep it simple, stupid. The best thing anyone can tell you, for any kind of product. Make it do only a couple of required features, and make that features well. Everything else doesn’t need to be done, at least at the moment. Don’t overthink the implementation, there are many currents in the rails development world which pull to this side or the other, but in this case, i must lean to @dhh and the pure rails way. You can optimise and improve later, after you have a product that is selling, and only the things that have to be optimised at the moment to keep the product running smooth.

Time is scarce, so make use of it

You don’t have time, as you are reading this, you have less and less of it. If you are still wasting it on nonsense, you won’t accomplish anything tangible. We had about 9 hours to make the application, and looking back, it was a couple of hours more than we needed, but we wasted time on initial configuration, setting up stuff, design. Lesson learned from this, Do the thing you are best at, and delegate everything else, if you can’t design to save your life, hire a great designer. If you can’t code, hire a great programmer. Just go outside, mingle with the community and you will surely find someone to team up with, if that isn’t the case, ask some of your acquaintances or friends, they will probably know someone who can help you build your dream.

Have a great team

The crucial thing any team needs is great communication, you don’t need ninjas, rockstars and whatnot. Anyone can build a web app, including high school kids who did a great job yesterday, i’m really happy that kids are going this path, as that will make their lives better.

Have fun

The main thing you are building a software product shouldn’t be money, or investors, but to have fun while doing it, if you aren’t having fun in your life, what is it worth to you then. I really like this job, and the people in the community are nice, if you are nice to them.

Final notes:

We had fun, we worked hard, i was swamped after spitting ruby code for 9 hours straight, and the experience was great. I met new people, had some interesting conversations, and saw other technologies people used to solve the same problem. We finished second, with a point difference of 15 points(the total possible was 1000), but it doesn’t really matter. The real reward is participating, and staying until the end, giving your best to solve the problem in hand, and supporting your team, as much as you possibly can.

Running a Freelance Business

| Comments

So, you have decided to start freelancing? I am really happy for you! It is a great choice, one of the best work related decisions I’ve made in my life. You maybe have some clients, maybe you just got laid off, and want to try this cool and fun freelancing life everyone seems to talk about. There surely isn’t much about it, you have a client, you work for some amount of time for that client, and get paid for the work. And you will be doing only the things you love, none of that crap on that ancient architecture your last boss was making you do. And you will work for whoever you want, because you are the boss now.

Yes, you have read that well, you are the boss now, and the CEO, and the CFO, and every other department that existed in the regular job you used to work. You also get to be the cleaner, and the system administrator.

How will you ever learn all of that, or even know everything there is to be done? The easiest way is to find someone in the same business you want to get into and ask them. Most people will gladly help, because they don’t mind helping out someone in need. Some of them, well, won’t help you, maybe even undermine you or your work, but, c’est la vie, some people are just assholes and you have to get over it. The sooner you grow a thicker skin, the better for you. So when you find out everything there is, and that depends from country to country so I won’t get into details about what needs to be done here, you have to figure out how to do it. Let’s get to that now.

You can, and should outsource a lot of that work, let the people better than you do their jobs and pay them for your own piece of mind. Accounting, legal, even assistant work can be outsourced to other people, freelancers or companies. They are professionals, like you are in your field, and should be on the edge of their domain, so you don’t have to. For example, I know very little about the process of accounting, I could if I wanted to, as could almost every one of us, but we don’t, because we have other stuff to think about, learn about, and to run our now business. Or law, which I know nothing about, but I’m sure a lawyer knows everything, or can refer me to the one that does.

So, when you have outsourced everything that someone else can do instead of you, there is still some work for you to do. Finding clients, marketing, scheduling, it work, being the CEO and the secretary at once, and taking care of yourself, as you are now your company’s best asset. I’ll get to those in my next couple of posts, because I don’t want you to fall asleep reading.

Working Remote

| Comments

You are surely tired of your commute, every day, waking up way before it’s convenient for you, cramming in public traffic, with people around you, wasting your precious time day after day. I had a 10 minute walk to the last place I worked at before going freelance, and it was nice, the commute before that was 45 minutes each way. But even that, being tied to one place, for 8 hours each day, at a fixed time, can be nauseating. There is a solution: Remote Working.

As you are aware, many companies nowadays offer the option for you to work remotely full time. As a freelance consultant, this is probably the most common way to work. Now, by saying remote, I don’t mean only and always working from your home, but working from a place that is not your main office, that can be a lot of places. Some people prefer coffee shops, some like me, really love to work from home, some go to a co-working space, whatever floats your boat.

So here are some benefits that you will see immediately or after some time, and pitfalls that you can encounter in your remote working life if you don’t take care of yourself.

Benefits

  • Less time commuting == More time spent with your family
  • No commuting expenses
  • Ability to choose the best time of day when you are most productive
  • Less stress and interruptions
  • Less meetings
  • Your written communication levels rise to the roof
  • You learn how to work better

Pitfalls

  • Not being able to separate work from private life
  • Isolation from other people can affect your mental health in a bad way
  • Letting yourself go physically

I am still a lousy writer, Jason and David are far better than me, so if you want to really learn about remote work, and everything it carries with, go and read great book on this subject Remote: Office Not Required by guys from 37signals.

Why Would You Want to Become a Freelancer?

| Comments

So what are your top reasons you want to become a freelancer? Feel free to leave them in the comments section below. I will briefly give you my reasons for doing it over the next couple of posts.

Be your own boss

The main reason everyone quotes is being fed up with the management at their current place of work. That may be due to a lot of reasons. For example: Stuck on boring projects; Can’t work from home sometimes; Don’t have a flexible schedule; You can’t implement the new and hip technology you read about last week, because you are stuck doing a VB6 project; And this list goes on and on…

The good parts

Being your own boss can improve that situation a lot, you get to choose the projects to work on, the clients to work with and the technologies to implement those projects to some extent. You get to choose when you work, and where you work from.

The bad parts(not really)

You are your own boss, you are the one to set the working schedule, organize yourself, and be proactive with work. There is no Boss telling you what you are going to work on next. Also you will find that you have to work on some other issues, as you have to run a company right now, a one man company of yourself, you are your own boss right now, and manager, HR, and marketing. Each client is a kind of a boss, as you are responsible to them for the work you are contracted to do.

The cure

Hire an accountant, and outsource as much stuff as you can. Time you spend on learning your skill, they spend on learning their skills. Don’t do everything by yourself, and remember, always be polite.

Flexible working hours/location

This is also a classic. All the freelancers out there seem to work whenever they want, wherever they want.

The good parts

You work whenever/wherever you want, you can travel around the country, or even abroad, and your work won’t suffer, your clients may not even notice that you are 5000 km away from the place they think you are. But it really doesn’t matter. Work happens where it happens for you, and it’s in your and your clients’ best interest to be as productive as you can for them, and for yourself, of course.

The bad parts

You can work the whole day, there is always something to be done. First you forget lunch, then you forget your kids big game or play at school, as you have so much work to do. If you don’t plan your time you will loose your health/family and everything.

The cure

Make a schedule and stick to it. Being constrained to work 5 or 6 hours each day makes you the most productive machine there is, because you haven’t got more time, just those 6 hours each day, so about 30 hours a week.

This is it for this post, I will continue writing on this subject and the tools to help you while freelancing or being a remote worker.

Override Https Errors for Regular Http Calls

| Comments

Let’s say you are building a web app that has some secure user data involved in the picture. You have to secure it with https, that is a necessity. So what happens when you have to include some outside service into your https only application, and the service sadly doesn’t have an https site, or maybe it has a self signed certificate? The error pops up, something in the context of This page is only partialy secure. There is a way to override this, but you are doing it at you own risk. You really should use only verified https resources in your public facing sites.

There can be many reasons why you would go with this solution, and i’ll leave them to you to find that out by yourself, i’m just giving you the hammer.

So, you want to override https calls in your app, and it’s a rails app(this approach can be done using sinatra or anything else ruby based, if you don’t know how to implement it, contact me and i’ll try to help)

Basically you want to override the outside http call with a call to your own application, yes this can hurt your performance, but not having a green icon in the address bar can hurt you even more. I’ll make an example with a simple JSON call to an external service, but it can be done with any call.

First you should set up a controller to handle these requests, lets say ExternalResourcesController make an external_json method and add it to the routes.rb file, of course you need net/http and uri for making the remote calls.

app/controllers/external_resources_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
require 'net/http'
require 'uri'
class ExternalResourcesController < ApplicationController

  def external_json
    options = {
      # fill your options with the params you are sending from the application
    }
    uri = URI('some external json service url')
    uri.query = URI.encode_www_form(options)
    resp = Net::HTTP.get(uri)
    render json: resp
  end
end
config/routes.rb
1
  get 'external_resources/external_json', to: 'external_resources#external_json'

This approach also gives you the benefit of not having to send and expose all parameters you are sending in client facing JavaScript, and can only send the dynamic ones. That can pay off if you are using this call more than once.

And you can call this from your CoffeeScript very easily:

app/assets/javascripts/ajax.js.coffee
1
2
3
4
5
6
  json = $.ajax
    url: "/external_resources/external_json"
    dataType: "jsonp"
    data:
      first_param_name: "I'm a parameter"
      second_param_name: "I'm a parameter too"

Once again, you should only use this approach if you really, really know what you are doing, i’m not liable for the problems you can cause.

Build Your Career (You Can Do Better)

| Comments

Let’s get this clear, this is not a rant against anyone, this is just a statement. But you must realize this, it is not easy and this is not a one week fix. Also, I’m not talking about leaving your job and finding a better one, but improving yourself as a developer. If that consequently gets you a better job, be it that way.

The first thing you need to do is decide for yourself that you want to do it. There are lots of 9-5 developers out there that write their amount of code while at work, then clock out and they are done. I assume you are not one of them.

So how do you do it? I don’t know yet. I’m trying to find out just like you are. Writing a blog is a good thing, so you will learn to articulate your thoughts, or so they say. Don’t be discouraged by the lack of topics, or afraid of bad reception, you want people to respond to your work, so you can improve it and be better at it.

Be constructive while appraising someone’s work, maybe it’s the best they have it in them, or maybe it could be a start of a great career and you ruin it with your critic. Talking about that, develop a thick skin, learn a way do weed out non constructive critic, and take the one you get in a best way intended. Not everyone is a bestseller writer, or a computer language creator.

Invest yourself into opensource projects, there are lots of resources on starting out. You can join or even start a local developers or something_users group, something being a language or framework you like and use. But first and foremost, you must be open to learn, every day everything that crosses your path is a chance to learn. I’m not talking about code or tools or even technology in that sense. If you’ve got the time take a look at the Passionate Programmer, it’s a great book by Chad Fowler. He is also posting the chapters free on his blog for people to read. I can’t recommend this book more.

Learn a new programming language, learn a functional programming language, make a mobile app, make a desktop app, make a web app, step out of your comfort zone and take a look how other developers are doing it.

Go outside, take a deep breath, exercise, take care of your health. Read another book: The Healthy Programmer, and enjoy your life a bit differently than while sitting in a chair in some cubicle in the middle of nowhere.

Do some freelance work, on the side or full time, that will give you the opportunity to try out new technologies, learn how to deal with clients, learn project management, estimating, scheduling and everything you are not doing while just coding 9-5.

So the conclusion is, learn every day, learn something different, step out of the box and be yourself, the best you can be. You can leave a dent in the universe, maybe a small one, but it doesn’t matter. Just try and not be a drone.

Dynamically Moving Div With jQuery

| Comments

Surely there has been a instance when you are creating an application that has a sidebar and a main content div. In the case of content being too long, the useful sidebar info can get left behind when you scroll down to see the other content.

In that case, you need to have some solution to scroll the sidebar content down as the user scrolls down. You can go with something like:

1
2
3
.movable-div {
  position: fixed:
}

And that will work, if the sidebar content is fixed to the top of the page. If not, you need something to know when to stick the content to the top of the page and when to unstick it, as the users srolls up.

Think of Yelp search page, and their map that smartly sticks to the top of the page when you scroll. So you need to use some JavaScript to achieve that. I chose jQuery for that job and wrote a simple helper to achieve that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// we need to fix the distance from our div to the browser top
var baseTop = $("div#sticky").offset().top;
$(window).scroll(function () {
    var top = $(window).scrollTop();
    if (top >= baseTop) {
        $("div#sticky").css({
            "position": "fixed",
                "top": "2px"
        });
    } else if (top < baseTop) {
        $("div#sticky").css({
            "position": "",
                "top": ""
        });
    }
});

For this to work, your #sticky div must be nested inside another one in the sidebar, let’s call it #sidebar so it wont pop out to the left while you scroll down.

I’ve made a jsfiddle so you can take a look at it in action. I’m really no front-end guy so please don’t take my div coloring skills against me.

Resources: Sticky div jsfiddle

Calculating Distance Using Geo Coordinates in Ruby

| Comments

As the social part of the sites is growing stronger, everyone of us has to include a user’s location of some sort into the application. There can be many reasons for that, be it location based search, advertising or something else unrelated. But mark this, you will have to deal with locations in the future.

I won’t get into the details of how to get the user’s latitude and longitude, but geocoder gem could be helpful for you.

I have found one JavaScript solution with the descriptions of what are the different implementations of the calculation and which one is more correct so I won’t get into the explanation. You can check the explanation and even more stuff you can do with 2 geo coordinates on the Movable Type Scripts

The distance can be calculated using 3 formulas, Haversine, Spherical Law of Cosines, and Equirectangular approximation

The prerequisites we will need are degree to radian conversion which is easily done with degree / 180 * Math::PI but to make the code easier to write we can monkey patch the Float with to_rad method which will calculate this for us. We could use refinements, or make a method object and not pollute the global space but we can leave it like this for now.

1
2
3
4
5
class Float
  def to_rad
    self / 180 * Math::PI
  end
end

After we have done the prerequisites let’s assume that we have two objects, and each one has a latitude and a longitude. For the sake of this post we can make them a hash with two keys latitude and longitude. And we take the earth radius as 6371km

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Geodistance
  include Math

  attr_reader :from, :to, :lat1, :lon1, :lat2, :lon2
  RADIUS = 6371

  def initialize(from, to)
    @from = from
    @to = to
    set_variables
  end

  def distance(type = 'haversine')
    begin
      self.send(type.to_sym)
    rescue
      raise NotImplementedError, 'The type you have requested is not implemented, try "cosines" or "approximation", or without params for "haversine"'
    end
  end

  private
  def haversine
    d_lat = (from[:latitude] - to[:latitude]).to_rad
    d_lon = (from[:longitude] - to[:longitude]).to_rad
    a = sin(d_lat / 2) * sin(d_lat / 2) + sin(d_lon / 2) *
        sin(d_lon / 2) * cos(lat1) * cos(lat2)
    c = 2 * atan2(sqrt(a), sqrt(1-a))
    RADIUS * c
  end

  def cosines
    acos(sin(lat1) * sin(lat2) +
         cos(lat1) * cos(lat2) *
         cos(lat2 - lat1)) * RADIUS
  end

  def approximation
    x = (lon2 - lon1) * cos((lat1 + lat2) / 2)
    y = lat2 - lat1
    sqrt(x * x + y * y) * RADIUS
  end

  def set_variables
    @lat1 = from[:latitude].to_rad
    @lat2 = to[:latitude].to_rad
    @lon1 = from[:longitude].to_rad
    @lon2 = to[:longitude].to_rad
  end
end

As you can see by calling the distance method with all 3 parameters, each one will produce a slightly different result. As they say, the haversine one should be the most accurate, but take caution. I would like to benchmark them some day and see which one calculates the result faster.

Thanks to Movable Type Scripts for providing the JavaScript code and all the insight. I just did a rewrite in Ruby.

Rails Integration Testing With Minitest::Spec and Capybara

| Comments

So you want to do integration testing for your application, good for you. If you have chosen Minitest and it’s specing DSL MiniTest::Spec as your test framework here is an example how to setup the integration tests to run fairly fast. Integration tests are similar to Cucubmer features, if you have used that before. I just like this style better because Cucumber, IMO adds too much noise, but it serves you as application documentation. I will also user Capybara for the webpage testing. Because we are using minitest-spec-rails gem, we don’t need to tinker with the config/application.rb and test settings, because ActiveSupport::TestCase is a subclass of Minitest::Spec

First we will set up the gemfile, with the needed gems( I also use guard for my automated tests, but it’s worth writing another blog post, soon hopefully)

1
2
3
4
5
6
group :development, :test do
  gem 'minitest-spec-rails'
  gem 'capybara_minitest_spec' # for capybara integration and spec matchers
  gem 'capybara-webkit' # for headless javascript tests
  gem 'turn' # for prettier test output
end

After that we need to set up out test/test_helper.rb to use Turn and capybara

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'rubygems'
require 'rails/test_help'
require 'minitest/autorun'
require 'capybara/rails'
require 'turn'

class ActionDispatch::IntegrationTest
  include Rails.application.routes.url_helpers # for x_path and x_url helpers
  include Capybara::DSL
  include PossibleJSDriver # switching Capybara driver for javascript tests, look below
end

# switching to the javascript driver in integration tests
module PossibleJSDriver
  def require_js
    Capybara.current_driver = :webkit
  end

  def teardown
    super
    Capybara.current_driver = nil
  end
end

After you have everything set up you can use all of this in your integration tests, here is an example of one integration test, without and with javascript browser turned on(require_js turns on the webkit driver)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'test_helper'
class LoginTest < ActionDispatch::IntegrationTest
  before { visit login_path }
  describe "signup text" do
    it "must have a signup text" do
      page.must_have_content("Don't have an account?")
    end
    it "must have a signup link" do
      page.find_link('Sign up').wont_be_nil
    end
    it "signup link must go to the signup path" do
      require_js # this one turns on the webkit javascript driver
      click_link('Sign up')
      current_path.must_equal(signup_path)
    end
  end
end

I have tested the integration test speed with :webkit as a default capybara driver and it runs at the same speed as the normal :rack_test driver, so you can go that way too.

Resources used:
https://github.com/metaskills/minitest-spec-rails
https://github.com/blowmage/minitest-rails
https://github.com/blowmage/minitest-rails-capybara
http://stackoverflow.com/questions/5655154/how-do-you-perform-javascript-tests-with-minitest-capybara-selenium/13296544#13296544
https://github.com/thoughtbot/capybara-webkit

I Just Joined Toptal.com

| Comments

Toptal is a relatively new company, similar in many ways to other freelancing sites available, but it has a twist.

I received an email from a recruiter last month and after a few hours inspecting the site, and watching the CEO’s talk at the Harvard Business School http://youtu.be/Ffjx_hl3IE8 i decided to contact them. I first had a nice chat with the recruiter explaining in depth what the company does and what can be our mutual benefits if i continue to pursue the arrangement. Later that day i was contacted by the CTO and scheduled a skype call with him. The skype call was a first test, Toptal cares that all developers are very fluent in English, not only written, but also in spoken form. The interview was no stress at all, a standard chat between two engineers that just met. After that i received the next test, solving some automated tests.  The tests weren’t really complicated but the time is limited to 45 minutes, i could write about the perils of automated testing, but that isn’t the case there, it’s just one of the screens. Interview number 3 was a pair programming session where another developer joined my shared screen session and gave me assignments, also solving some algorithms, but with him watching me writing code. After i passed that test, there was another, to create an AJAX web application with REST API and authentication. I did my best on a limited schedule and passed that test too and became a member of a growing number of their network of senior freelance developers.

To save you the trouble, i’ll write something about Toptal and why they are not the same as Elance, Odesk or other freelance sites. Toptal hires freelance engineers, then tests them, and has people working with them and the clients to find the best match for the engineer and the client. That way you already get tested and able engineers to work with them. Also the engineer is instructed in detail about the job he is interviewing for and can prepare for it. All of the recruiters are engineers so it makes the stuff easier because everyone understands the problems. You as a client, have the possibility to try out a few developers until you find one that suits you and can hire them either part or full time whatever suits you.

The bottom message is: If you are in need of top talent to develop you application or you are a skilled developer who wants to work for some of the best companies in the world join Toptal and give us a try.