How to make objects behave like ActiveRecords models…

…and make them usable with rails form helpers as well.

1.) Use ActiveModel

Add

    include ActiveModel::Validations

to the top of your class in question. Now you have all the standard validations like

  validates :field, presence: true

at your hands.

2.) Make it possible to initialize your objects ActiveRecord style:

    def initialize(attributes = {})
      attributes.each do |name, value|
        send("#{name}=", value)
      end
    end

3.) Make them usable with rails form helpers

I am not sure if this the “right” way to do it, however it worked pretty well for me.
You need to add

def to_key; nil; end

otherwise rails will complain if you use this object with a form helper:

undefined method `to_key' for

Of course this doesn’t have to be nil, it can be anything that works as a key.

Posted in rails, Ruby | Leave a comment

Elastic Beanstalk and Ruby / Rails – Stay away

Recently I wanted to switch our deployments from manual setups to something more suitable and automatable in terms of scaling, process management and so on.
Since we were already on EC2, Elastic Beanstalk was the first thing that came to mind:

From the docs:

AWS Elastic Beanstalk is an even easier way for you to quickly deploy and manage applications in the AWS cloud. You simply upload your application, and Elastic Beanstalk automatically handles the deployment details of capacity provisioning, load balancing, auto-scaling, and application health monitoring.

Seems like a good fit. Unless it isn’t.

So what’s the problem with Elastic Beanstalk?

Nothing f***ing works. Nothing f***ing works.

First of all, you need to understand one thing: I tried to get a basic rails app up and running. I did absolutely nothing by hand – I only used amazon’s built-in steps. This means I exclusively used amzon’s webinterface. No manual fumbling on the instances itself.

Now, even with this basic setup I had problems all of the time. Below a list errors that randomly popped up and in the same manner disappeared again from deployment to deployment:

All of a sudden my ruby setup seems borked big time:

2013-04-26 08:18:48,080 [INFO] (29466 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Output from script: /usr/bin/rake:9:in `require’: no such file to load — rubygems (LoadError)
from /usr/bin/rake:9
Rake task failed to run, skipping database migrations

WTF?

Events / logs are not reliable:

Trying to get the logs after a failed deployment gives me:

Failed to pull logs for environment instances. Reason: Some instances have not responded to commands. Responses were not received from [i-52f6fc18].

Or:

In the “Events” Tab I see:

Failed to deploy application

However there is NO error in the logs and despite what the “Events” say, deployment apparently was successful

All of a sudden my rails setup is borked:

From the logs (after more than a dozen deployments):

2013-04-19 10:25:38,717 [INFO] (1831 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Output from script: rake aborted!
No Rakefile found (looking for: rakefile, Rakefile, rakefile.rb, Rakefile.rb)

(See full trace by running task with –trace)
Rake task failed to run, skipping asset compilation.

Apart from this seemingly random bugs which come and go as they please, I am pretty sure that almost no one is using EB for ruby / rails. You can google for any problem you have and you find nothing. It seems like amazon just added this specific layer because it is hip.

All in all, using Elastic Beanstalk was a horrible experience and I can’t recommend it to anybody. Funny enough I tried out amazon opswork after Elastic Beanstalk and so far, this has been nothing short of fantastic.

Long story short: If you want to use amazon deployments mechanisms, use opswork, not Elastic Beanstalk.

Posted in Uncategorized | Leave a comment

Why you should always merge feature branches as one atomic commit

Since I’ve had this discussion quite often I thought I’d summarize my arguments here

Posted in Uncategorized | Leave a comment

My glorious vim setup

Ok, so maybe it’s not that glorious.

Plugins:

Configuration:

” Pathogen set up
call pathogen#infect()
” syntastic setup
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_auto_loc_list=1
” nerdtree setup
map :NERDTreeToggle
” Needed for autoclose to work, see https://github.com/tpope/vim-endwise/issues/25
autocmd FileType ruby,eruby :let g:AutoCloseExpandEnterOn=”"
” My color scheme of choice
let moria_style = ‘white’
colo moria
” Tab settings: We want soft tabs with an indentation of 2.
set expandtab
set shiftwidth=2
set softtabstop=2
set tabstop=2
” Make vi shell behave more like command prompt
set shellcmdflag=-ic
” Show line numbers
set number
” Show special characters in the file.
set list
” Turn on syntax highlighting
syntax on
” Don’t tell me how to autoindent
set noautoindent
” Highlight search results
set hls
” Autodetect file types
filetype plugin on
” Add additional mappings for e.g. nerdcommenter
let mapleader = “,”
” Show us trailing whitespace, we don’t want that garbage in our source code
highlight WhitespaceEOL ctermbg=red guibg=red
match WhitespaceEOL /\s\+$/
” Highlight settings when selecting text
hi Visual cterm=reverse term=reverse

Posted in vim | Leave a comment

Here is why you should never outsource coding

…unless you really made sure that the team is actually any good. If you don’t, you get back gems like below.

We like it explicit, don’t we:

public boolean gpsCheck()
{
  if (lm.isProviderEnabled( LocationManager.GPS_PROVIDER )==true )
    return true;
  else
    return false;
}

Why restrict yourself to just one way of saying that something doesn’t exist?


if (price != null || !price.equals("null")) {
if (slogan != null || !slogan.equals("null")) {
if (year != null || !year.equals("null")) {

This is how you should handle email validations:


private void sendInvitation(final String email) {
  if (email == null || email.length() < 5 || !email.contains("@")) {
    Utils.displayMsg(context, R.string.invalidEmail);
    return;
  }
  else if (!email.contains("@")) {
    Utils.displayMsg(context, R.string.invalidEmail);
    return;
  }
  // ...
}

(I especially like the guard in the “else if”. Just to make really sure that we have an @ in there.)

It’s always a good idea to name your variables like existing core java classes:

private String Long;

public String getLong() {
  return Long;
}

public void setLong(String Long) {
  this.Long = Long;
}

Better double check that we really return null if the result is null:

public ArrayList<String> getResult() {
  if (result == null)
    return null;
  return result;
}

If you don’t know how to actually load some kind of configuration in Android, just put api keys in your locale files, because you know how to load those, don’t you?

<string name="GoogleMapAPIKey">My_God_Damn_Api_Key>

Good stuff, isn’t it?

Posted in clusterfuck, java | Leave a comment

Contributing to Rubinius – work on Ruby 1.9 compatibility

So, recently I got fascinated with Rubinius. In all brevity I’d like to show all necessary steps to contribute to Rubinius by helping to make Rubinius Ruby 1.9 compatible:

1.) Check out the repo

git clone https://github.com/rubinius/rubinius.git

2.) Switch to ruby 1.8.7 to build Rubinius (1.9 is currently not supported):

rvm use 1.8.7

3.) Build it:

rake build

4.) Run all specs to make sure that your set up is correct – everything should be green:

rake spec

5.) List all specs that fail for Ruby 1.9:

bin/mspec tag --list fails -tx19 :ci_files

6.) There should be quite some output – pick a failing spec, e.g.:

Proc#== returns true if both procs have the same body and environment

7.) Find the spec in question e.g. by grepping ( I haven’t found a more convenient way so far, adding “-V” for verbose to mspec is too noisy for me)

grep -r 'if both procs have the same body and environment' spec/

8.) Run the spec in question and see it fail:

 bin/mspec -tx19 spec/ruby/core/proc/equal_value_spec.rb

9.) Create a git feature branch

git checkout -b fix_proc_equality

10.) Fix the error…:-)

11.) Build and re-run the spec:

 rake build; bin/mspec -tx19 spec/ruby/core/proc/equal_value_spec.rb

The spec should pass. Then re-run all specs with `rake spec` to make sure you didn’t accidentally break something else.

12.) Push that branch

13.) Issue a pull request on github

14.) Enjoy yourself when your PR got accepted..:-)

Posted in Rubinius | Leave a comment

Over-Testing

Very good article about over-testing by DHH himself: Testing like the TSA

Posted in rails, TDD | Leave a comment