A GIF is worth a thousand screenshots

Posted about 1 month back at opensoul.org - Home

Did you know that GIFs have productive uses? Yep, deal with it! Lately, I have been including GIF screencasts on pull requests that include user interface changes as a way to clearly demonstrate the changes.

It's an extermely effective way to communicate what has changed. These screencasts have other uses, such as showing how to use a feature or demonstrating a bug.

There are a lot of ways to make a GIF screencast, but LICEcap is the best tool I have found found. It is not the prettiest piece of software that I have ever laid eyes on, but it just works and makes fantastic GIFs. The GIF above is 26 seconds long, great quailty, but only 500 KB.

Episode #443 – February 25th, 2014

Posted about 1 month back at Ruby5

In this episode we cover new Rubies and rSpec, Ruby’s Demise, AdequateRecord, and a Ruby Heroes reminder.

Listen to this episode on Ruby5

Sponsored by TopRubyJobs

If you're looking for a top Ruby job or for top Ruby talent, then you should check out Top Ruby Jobs. Top Ruby Jobs is a website dedicated to the best jobs available in the Ruby community.
This episode is sponsored by Top Ruby Jobs

RSpec 2.99 and 3.0 beta 2

Late last week Myron Marston and the RSpec team released versions 3.0.0beta2 and 2.99.0.beta2.
RSpec 2.99 and 3.0 beta 2

Ruby is Legal (2.1.1)

Our Ruby is all grown up. Yesterday was ruby's 21st birthday. To celebrate they released version 2.1.1 along with patch releases for 2.0.0 and 1.9.3
Ruby is Legal (2.1.1)

Rumors of Ruby’s Demise

Avdi Grimm wrote a blog post about the 'Rumors of Ruby's Demise' where he talks about the hype around other languages, specially ones with built-in support for concurrency like Erlang or Scala, and how some people in the community see that as sort of a threat to Ruby.
Rumors of Ruby’s Demise

AdequateRecord

Last week Aaron Paterson released a fork of ActiveRecord that can handle twice as many requests per second.
AdequateRecord

Ruby Heroes

Please take a moment to nominate someone that's significantly contributed to our community this past year for a Ruby Hero Award. The awards with be given at RailsConf in Chicago.
Ruby Heroes

Thank You for Listening to Ruby5

Ruby5 is released Tuesday and Friday mornings. To stay informed about and active with this podcast, we encourage you to do one of the following:

Thank You for Listening to Ruby5

EmberJS with a Separate Rails API

Posted about 1 month back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

We just wrapped up a large client project using EmberJS and we learned a few things that are interesting to share.

Ember made this project easier. There are times that a JavaScript framework is unnecessary and there are times that it makes the code much cleaner. This was the latter.

Split Development

We built our API and our JavaScript application as two completely separate applications. We had one repo that held a very basic Rails application with Ember on top and another repo that held the API built in Rails.

Rails instead of Yeoman, Grunt, Brunch, etc

There are a lot of front end development tools that will allow you to build an EmberJS application using CoffeeScript, Sass and the other tools that we like to use on projects. After evaluating them we settled on using a basic Rails application instead; primarily for simplicity. The project had a short timeline and we didn't want to have to worry about another tool that we were not familiar with. In the future I would love to try building an Ember UI using a front end tool such as Tapas with Ember but we didn't have any complaints with using Rails in this case and it made our stack a bit simpler to use.

For Ember in our Rails app we used the ember-rails gem. It provides a basic folder structure for your Ember application inside the app/assets/javascripts directory. The directory structure is similar to a Rails application as you can see below.

controllers/
helpers/
components/
models/
routes/
templates/
templates/components
views/

The one thing that is strange when using the gem for a UI only application is that your app/ directory in Rails is basically unused except for the app/assets/javascripts/ where all the actual work will happen. Another project, EmberAppkitRails, solves this issue by putting the app/ directory into asset pipeline. This is an interesting idea. The gem is pre-1.0 so the API could change.

Ember-rails also provides configuration variables for using the development or production version of Ember depending on your current enviroment. This is nice so that your Ember debug information is automatically removed in production.

Fixtures in Development

To allow rapid development, we built the UI in Ember using only fixtures in Ember Data. This allowed us to very quickly build out complex interactions without having to worry about the API being in place. This was a huge help in moving fast and later we backfilled the API. Being able to change property names without having to worry about migrations or outside API changes was very efficient. An Ember Data fixture is a simple JSON object and you can quickly modify it to your needs. It also handles has many and belongs to references using the IDs of other elements.

App.User.FIXTURES = [
  {
    id: 1
    email: 'user@example.com'
    posts: [1, 3]
  }
  {
    id: 2
    email: 'secondUser@example.com'
    posts: [2,4]
  }
]

App.Post.Fixtures = [
  {
    id: 1
    title: 'The Art of Vim'
    user: 1
  }
  {
    id: 2
    title: '15 Minute Blog in EmberJS'
    user: 2
  }
]

There are downsides to this approach. The first one is the backfill process. We waited too long in the project to connect our API to Ember and ran into issues.

The other problem is that by having the applications in two seperate repos, you can't easily have a full integration test. In order to do this you would need to run both applications on the same machine simultaneously. You would also need some way to make sure that both of the applications were on the same revision for the test.

We decided to test the apps seperately and trust that the API is what we've said it was. This can be frustrating but in our case, it didn't turn out to be a real problem. Once you have wired your API to the UI, you should never change your UI without also changing the API. This was enforced in code review only.

CoffeeScript

I love CoffeeScript and as a company we have embraced it for our all our projects. Ember is no exception to that. CoffeeScript made our Ember application more readable and easier to work with objects. The only thing that is odd is the syntax for a computed property, but that is a minor issue and we quickly adjusted to seeing it as normal.

fullName: (->
  "#{@get('firstName')} #{@get('lastName')}"
).property('firstName', 'lastName')

Fast Tests!

By removing the API from the UI application, we were able to write feature specs entirely in CoffeeScript. This was a huge benefit to the overall success of the project. We could test every interaction in our app precisely and not have to worry about the normal overhead associated with those types of feature specs. The specs only had to deal with JavaScript so it was really fast. A full rake for our UI application was 32.770 seconds including starting the Rails environment. The suite had a total of 71 examples, most of which were feature specs.

Testing in General

We found Ember to be very easy to test in general. Most things break down to Ember.Object and it was easy to grab a controller in a test and verify that a property works as expected. Because we wanted to use Mocha with Chai BDD matchers instead of QUnit, the initial test setup was a bit complex but after using Konacha with a Mocha adapter, it was smooth sailing. The extra setup time for Mocha over QUnit was definitely worth it. The syntax has a much more readable format.

describe 'AggregateStatsController', ->
  describe 'summed properties', ->
    beforeEach ->
      stats = []
      stats.push Ember.Object.create
        clicks: 2
        cost: 1.99
      stats.push Ember.Object.create
        clicks: 4
        cost: 2.00

      model = Ember.Object.create(dailyStats: stats)

      controller = App.__container__.lookup('controller:aggregate_stat')
      controller.set('model', model)

    it 'will sum the number of clicks in the model', ->
      expect(controller.get('clicks')).to.equal(6)

    it 'will sum the cost in the model', ->
      expect(controller.get('cost')).to.equal(3.99)

Feature specs were also very easy to handle. Ember has built in integration test helpers that worked for most of our needs and we used jQuery to augment them in our expectations. The specs were fast enough that we could test small details in the interface that we might otherwise want to omit. Being able to test all the UI interactions gave us a lot of faith in our codebase.

describe 'Navigating SEM Campaigns', ->
  before ->
    App.DailyStat.FIXTURES = [
      {
        id: 1
        clicks: 11
      }
      {
        id: 2
        clicks: 10
      }
    ]

    App.SemCampaign.FIXTURES = [
      {
        id: 1
        name: 'Opening Campaign'
        status: 'active'
        dailystats: [1]
      }
      {
        id: 2
        name: 'Final Sale'
        status: 'active'
        dailyStats: [2]
      }
    ]


it 'shows the daily stats information for campaign', ->
  visit('/').then ->
    clickLink('SEM Campaigns').then ->
      expect(pageTitleText()).to.equal('SEM Campaigns')
      expect(pageHasCampaignWithTitle('Opening Campaign')).to.be.true
      expect(statusFor('Opening Campaign')).to.equal('icon-active')
      expect(clicksFor('Opening Campaign')).to.equal('11')
      expect(pageHasCampaignWithTitle('Final Sale')).to.be.true

Naming your tests

Konacha and Teaspoon both have the downside of not showing a filename when a spec fails. This caused us a lot of pain when we first started so we decided on the convention of using the first describe docstring as the name of the file. In the case above our file would be named navigating_sem_campaigns_spec.js.coffee. This worked out great and made it much easier to find a failing spec.

Overall

Ember is far stabler than I would have imagined given that 1.0 was just released 6 months ago. If you have a project that is highly interactive and requires a lot of data binding, I recommend trying it out. The Ember community has been incredibly helpful on Stack Overflow, their forums and their IRC channel.

Spam improvements

Posted about 1 month back at entp hoth blog - Home

Howdy,

Today we deployed a number of improvements to our spam engine. As a result you should see a big decrease of false positives (real discussion incorrectly marked as spam). It is possible that you will also notice a slight increase of false negatives (real spam, not caught). As you continue marking those as spam the situation should rapidly improve.

We also added a new option: you can now ignore spam checking for a particular category. This is useful when you receive emails from an automated source (form, etc), which contains a lot of (sometimes malformed) HTML which may trigger some of our spam rules.

You will find this setting when editing a category:

Don't check for spam

As usual, if you have problems with spam on your site, please contact us. This includes:

  • Emptying a very large spam folder
  • Too many false positives
  • Too many false negatives

Thanks!

Of Late

Posted about 1 month back at RailsTips.org - Home

A lot has changed over the years. I now do a lot more than just rails and having railstips as my domain seems to mentally put me in a corner.

As such, I have revived johnnunemaker.com. While I may still post a rails topic here once in a while, I’ll be posting a lot more varied topics over there.

In fact, I just published my first post of any length, titled Analytics at GitHub. Head on over and give it a read.

Introducing Lotus::Controller

Posted about 1 month back at Luca Guidi - Home

Lotus development is going well. The experiment of open source a framework per month is sustainable. I have the time to cleanup the code, write a good documentation and deliver great solutions.

This month, I’m proud to announce Lotus::Controller.

It’s a small but powerful and fast framework. It works standalone or with Lotus::Router and it implements the Rack protocol.

Actions

The core of Lotus::Controller are the actions. An action is an HTTP endpoint. This is the biggest difference with other frameworks where they use huge classes as controllers. Think of Rails, where a single controller is responsible of many actions and holds too much informations. Lotus is simple: one class per action.

require 'rubygems'
require 'lotus/controller'

class Show
  include Lotus::Action

  def call(params)
    @article = Article.find params[:id]
  end
end

With this design I wanted to solve a some annoying problems.

An action is an object, whose ownership belongs to its author. She or he, should be free to build their own hierarchy between classes. Lotus offers Ruby modules to be included instead of superclasses to be inherited.

Smaller classes are high cohesive components, where the instance variables have a strong relationship between them. This level of isolation prevents accidental data leaks and less moving parts.

A tiny API of one method makes straightforward the usage of Lotus::Controller. Its argument (params), makes it easy to integrate with existing Rack applications. It returns automatically a serialized Rack response.

A side benefit of this architecture is to take over the control of instantiate an action.

require 'rubygems'
require 'lotus/controller'

class Show
  include Lotus::Action

  def initialize(repository = Article)
    @repository = repository
  end

  def call(params)
    @article = @repository.find params[:id]
  end
end

action   = Show.new(MemoryArticleRepository)
response = action.call({ id: 23 })

assert_equal response[0], 200

In the example above we define Article as the default repository, but during the testing we’re using a stub. In this way we can avoid hairy setup steps for our tests, and avoid to hit the database. Also notice that we’re not simulating HTTP requests, but only calling the method that we want to examine. Imagine how fast can be a unit test like this.

Exposures

Instance variables represent the internal state of an object. From an outside perspective we don’t know which is that state. The simplest and recommended way to get this information is to ask for it. This mechanism is called Encapsulation. It’s one of the pillars of Object Oriented Programming.

The instance variables of an action are necessary for returning the body of an HTTP response. While we’re creating that result from the inside of an action, we can access these informations directly. External objects can retrieve them with getters. These getters are defined with a simple DSL: #expose.

require 'rubygems'
require 'lotus/controller'

class Show
  include Lotus::Action

  expose :article

  def call(params)
    @article = Article.find params[:id]
  end
end

action = Show.new
action.call({ id: 23 })

assert_equal 23, action.article.id

puts action.exposures
  # => { article: <Article:0x007f965c1d0318 @id=23> }

No Rendering, Please

Lotus::Controller helps to build pure HTTP endpoints, rendering belongs to other layers of MVC. It provides a private setter for the body of the response.

require 'rubygems'
require 'lotus/controller'

class Show
  include Lotus::Action

  def call(params)
    self.body = 'Hello, World!'
  end
end

Views and presenters can manipulate the body of the returned response.

require 'rubygems'
require 'lotus/controller'

class Show
  include Lotus::Action

  expose :article

  def call(params)
    @article = Article.find params[:id]
  end
end

action      = Show.new
response    = action.call({ id: 23 })
response[2] = ArticlePresenter.new(action.article).render

Other features

Lotus::Controller offers a set of powerful features: callbacks, automatic management for exceptions and mime types. It also supports redirects, cookies and sessions. They are explained in detail in the README and the API documentation.

Roadmap

On March 23rd I will release Lotus::View.

To stay updated with the latest releases, to receive code examples, implementation details and announcements, please consider to subscribe to the Lotus mailing list.

<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css"/>

Avoid the Three-state Boolean Problem

Posted about 1 month back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Quick, what's wrong with this Rails migration?

add_column :users, :admin, :boolean

Yep - it can be null. Your Boolean column is supposed to be only true or false. But now you're in the madness of three-state Booleans: it can be true, false, or NULL.

Why to avoid NULL in Boolean columns

Boolean logic breaks down when dealing with NULLs. This StackOverflow answer answer goes into detail. For example:

  • true AND NULL is NULL (not false)
  • true AND NULL OR false is NULL

Fortunately, it's easy to fix.

NOT NULL

Adding a NOT NULL constraint means that you'll never wonder whether a NULL value means that the user is not an admin, or whether it was never set. Let's add the constraint:

add_column :users, :admin, :boolean, null: false

But now the migration doesn't run.

Set a default value

The NOT NULL constraint means that this migration will fail if we have existing users, because Postgres doesn't know what to set the column values to other than NULL. We get around this by adding a default value:

add_column :users, :admin, :boolean, null: false, default: false

Now our migration runs, setting all users to be not admins, which is the safest option. Later, we can set specific users to be admins. Now we're safe and our data is normalized.

What's next?

For more on the danger of null values, read If You Gaze Into nil, nil Gazes Also Into You. You can also browse our Postgres-related blog posts.

Episode #442 – February 21st, 2014

Posted about 1 month back at Ruby5

We will miss you Jim Weirich.

Listen to this episode on Ruby5

Farewell, Jim.

Posted about 1 month back at Phusion Corporate Blog

Today, the sad news has reached us that Jim Weirich has passed away. We’re incredibly sad about this as Jim was one of the nicest people we’ve got to know in the Ruby/Rails community when we first started Phusion. In keeping his memory alive, I’d like to reflect on a particular anecdote that made Jim especially awesome to us and most likely to you as well. I’m sure many of you who were fortunate enough to get to know him can relate to his kindness.

Back in 2008 when Hongli, Tinco and I set out to go to RailsConf to give our very first talk abroad, we met Jim in the lobby of the conference space. We had just attended a talk of his where he had gone through a myriad of valuable do’s and don’ts one should be aware of when giving a talk. These tips proved to be incredibly valuable to us in years to come, and we hope Jim knows how grateful we are for this.

Our talk was scheduled to be held the day after, and seeing Jim’s do’s and don’ts, we were suddenly confronted with how many embarassing “don’ts” we had in our slides. As Jim told the audience that it’s generally a good idea to avoid cliches such as having bulletpoint hell, stock images of “the world” and “business people shaking hands”, we felt more and more uncomfortable. Not only did we have a lot of bulletpoints, we even had an image of “business people shaking hands”… in front of “the world”. We basically tripped over every possible cliche in the book!

But hey, we still had 24 hours, surely we’d be able to fix this up right? Luckily, Jim had the demeanor of a big kind cuddly bear, so we felt compelled to walk up to him after his talk to ask for some help with our slides. Instead of brushing us off, Jim graciously sat down with us for about 2 hours in pointing out the things that could use improvement in the delivery of our talk. And understandibly laughed out loud at our slide with the business people shaking hands in front of the world. ;)

The next day, after giving our talk, we had people walking up to us saying that we killed it. In reality, it was Jim’s tips and kindness in sharing these tips that “killed it”.

We will miss you buddy.

Your friends, Tinco, Hongli and Ninh.

Low Power Custom Arduino Sensor Board

Posted about 1 month back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Last month we looked at using Arduinos to monitor bathroom usage at thoughtbot so employees could check bathroom availability at their desks. After we had a working prototype, power consumption was too high resulting in only a day of usage. It was also very expensive to reproduce if we wanted to expand our sensor network.

Lower Power, Higher Savings

The biggest power sucker was the XBee radio. It was always on and drawing about 50mA of current. The XBee Series 2 offers a bit more power savings when on and also has a more robust interface that allows us to put it in sleep mode. However, it still has a steep price. The better option is the nRF24l01+ series from Nortic. They are very inexpensive on Amazon.com, have an SDK for the Arduino, sleep mode capability, and gives us automatic transmission packet assemble, detection, validation, retransmission, and acknowledgement.

When using the nRF24l01+ board in conjunction with the Arduino Fio, there was large jump in power savings. Current consumption for the entire sensor board was down to around 5mA. This would yield about 80 hours of use on a 400mAh battery. That's only about 3 days until it would need to be recharged again. Still not so great. The final chunk of power sucking was being caused by the LED that comes on every Arduino to indicate power-on. Removing the LEDs and potentially destroying an expensive board didn't sound appealing. The best option was to design a custom Arduino board that would fit our use case instead of trying to mash together pre-made general purpose boards.

Introducing the thoughtbot Arduino Sensor Board

The custom Arduino board will have no LEDs for power savings. To keep it similar to other Arduino boards, it will use the ATMega328P 8-bit microcontroller and have the same pinouts on the connectors. It will have a connector for the nRF24 board for easily making it wireless. Finally, it will support LiPo rechargeable batteries and coin cell batteries.

Designing the Board

We used the free version of Eagle for the schematic capture and PCB layout. You can access the eagle files, Gerber files, and bill of materials in the repository.

Here is the schematic: Sensor Board Schematic

Here is the PCB layout: Sensor Board PCB

Assemble Your Own

We used OSHPark to fabricate the boards. They are inexpensive and relatively quick. We had our boards in less than 2 weeks. To make your own, upload the Gerber files to OSHPark. While you're waiting for the boards to arrive, place an order with DigiKey for the components. The list of components is also on the repository: BOM. You will also need a few other things to program the Arduino that you could order while you waiting. Read the Programming section for specifics.

Fabricated PBC

Soldering it Together

To solder together the board, you'll need a few tools:

Soldering Tools

Start with U1, the microcontroller. It will be the hardest to solder so make it easy on yourself and do it before there are other parts in the way. Align the chip so pin 1 is in the correct spot and that all the pins are centered on their pads. Use some tape to hold it in place. Next, apply flux to one side of pins. Then, touch the solder to the hot iron just to get a little bit on the tip of the iron. Then, place the tip of the iron on each pad and you will see the flux-soaked metal pull the solder over it. Move down the pins, touching each one until you see the solder flow over it. Touch the solder to the iron again if more is needed. Once you have one side of the microcontroller done, remove the tape and finish the other sides.

We used a volt meter to test the pins and make sure they were connected to the pads by testing that the resistance between the pin on the chip and a pad it connects to somewhere else on the board was 0. If you don't have a volt meter a visual inspection will be sufficient. If 2 pins were accidentally connected by too much solder, try to add flux again and re-apply the iron. If that doesn't work, soak up some of the solder using the copper braid. Apply flux, then put the copper braid on top of the solder and push down on the braid with the soldering iron. Make sure to hold the plastic case of the braid and that there is enough braid between the case and the soldering iron or you could melt the case. You should see the copper braid absorb the solder and turn tin colored. Remove the braid when you've soaked up enough and re-touch the pins with solder as needed.

Sensor Board with chip soldered

Next, solder the other tough components, U2 and JP9 (the USB connector). Move onto the small components, capacitors and resistors, and take on the biggest stuff last, the connectors. When soldering the other small components, tape can be impractical, so try putting solder on one pad first then, using the tweezers, slide the component in while heating the pad with the soldering iron. Then solder the other side.

Take care when soldering the LED and the capacitor C1. Both of these components have to be soldered in a certain orientation. C1 pad should have a white line closer to one pad and there should be a white line on one end of the part. Make sure these lines are aligned. The LED should have a line and a dot on the bottom of the part. The line should face toward power. The green line is somewhat visible in this image:

LED Direction

Once you're all done it should look similar to this:

Sensor Board completed

Programming

To use the board as an Arduino, you'll have to upload the Arduino bootloader onto the chip. You can do this with this programmer from Sparkfun. Plug it into J1 so that the cable goes over the chip. If you're not sure, check the pin mappings. It should look similar to this image:

Programmer Connection

Plug the USB cable from the programmer into your computer and burn the bootloader to the chip from the Arduino software. If you're having trouble making your computer recognize the programmer, look around the internet as there is a lot of support out there. Open the Arduino software, at this time the latest version is 1.0.5. In the menu, select Tools, Board, Arduino Uno. Then, Tools, Programmer, USBtinyISP. Finally, Tools, Burn Bootloader. After a bit of time the board should be programmed with the Arduino bootloader.

Now you have a fully functional Arduino board. To save space and cost on the board, we left out the FTDI USB to Serial chip. The Arduino software uses USB to Serial to program the devices. You can purchase one from Sparkfun or Amazon.com. The way the board was designed, you need to plug the FTDI board in upside down. If the board is not plugged in correctly the power pins will be misaligned and you'll risk damaging the processor.

FTDI Board Connection

To make sure everything works, plug in the FTDI board to you computer and open the Blink example from the Arduino software. Make sure the Arduino Uno is selected as your board and the correct serial port is selected in the Tools menu. Upload the program. Connect and LED in series with a resistor (330 ohms to 1K) between ground (GND pin) and pin D13. Make sure the cathode of the LED is facing toward ground. The LED should blink in 1 second intervals.

Conclusion

Your Arduino is ready to go! Have fun creating anything your mind can imagine! Next time we'll look at rewriting the software for the bathroom occupancy detector and creating a sensor network using this custom Arduino board and the nRF24 transceiver.

iOS Code Review: Loose Guidelines

Posted about 1 month back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

From time to time I've been asked to do an independent code review, to determine the overall health of a client's code base. Unlike a code walkthrough, where someone familiar with the code shows the main components, this is a code review where an outside expert examines the project, takes copious amounts of notes, and reports back either in written form or in a meeting with the team, depending on what the client wants.

This is separate from doing testing or any other sort of QA on the applications themselves. The idea is that you might have an application that works great and passes all kinds of acceptance tests, but is built in a such a way that future maintenance and enhancements will be difficult and/or costly. If we can identify problem areas in an application's source code, we can help set things on a better course. The sooner we can discover potential problems, the better. The experiences and guidelines described here are centered around iOS programming practices, but many of them apply to other sorts of projects as well.

The last time I did this, the client's budget was limited, so there wasn't time to do in-depth examination of every source code file in each of the clients's application. I had a lot of territory to cover, and not a whole lot of time. So, I decided to do it in two phases: First, I took an initial look at each project to establish a quick (if superficial) opinion of each project's health. After that, I dove deeper into each project, paying extra attention given to the projects that set off the most warning flags during the initial phase. This procedure worked pretty well, since I was able to report back with an approximate health level for each application, plus a lot of specifics for those that seemed to be in worse shape than the others.

The set of guidelines I'm outlining here are the kind of thing that anyone can do on their own codebase as well. If you don't understand what some of these points are all about, or why they're worth thinking about when it comes to your own apps, this could be a good time to improve your own skills a bit by thinking about some of these topics and looking for relevant discussion and debate (for example, on the internet).

Phase One: A Quick Look

To get a feel for the overall health of each app, do the following things:

  • Make sure all external resources required by the project (3rd-party code, etc) are fully contained within the app, or referenced through submodules, or (best of all) included via CocoaPods. If they're not managed in some way (e.g. CocoaPods) see if there is any documentation describing how to obtain and update these resources.
  • Open the project in Xcode and build it. Make sure the project builds cleanly (with no warnings, and hopefully errors).
  • Perform a static analysis in Xcode to see if any other problems show up.
  • Run oclint and see if this uncovers any other problems that Xcode's static analysis didn't reveal.
  • Examine the project structure. Do the various source code files seem to be placed in a reasonable hierarchy? The larger the project is, the more important it becomes to impose some kind of structure, in order to help outsiders find their way around.
  • Does the app have unit tests or integration tests? If so, run them and make sure they complete without any failures. Bonus points if tools are in use for measuring test coverage.

Doing all that should take several minutes for each app, regardless of the app's size, unless you encounter major problems somewhere along the line. Finding things that are not to your liking on one or two of those points doesn't necessarily mean that you've got a huge problem on your hands, but by considering your findings here you can start to get a sense of any project's overall "smell".

Phase Two: Diving Deep

After that, do a closer examination of each app, starting with the ones that set off the most warning flags in your head during the initial examination. You should look at every source code file (if you have the time to do so), reading through the code with all of these things in mind. You'll probably want to take notes as you go along, when you find things that need improving.

Objective-C

  • Are the latest Objective-C features from the past few years being used? This includes implicit accessor and instance variable synthesis, new syntactic shortcuts for creation of NSNumber/NSArray/NSDictionary, new syntax for array and dictionary indexing, etc.
  • Are instance variables and properties used in a consistent way? Does the code use accessors where appropriate, keeping direct instance variable access limited to init and dealloc methods?
  • Are properties declared with the correct storage semantics? (e.g. copy instead of strong for value types)
  • Are good names used for classes, methods, and variables?
  • Are there any classes that seem overly long? Maybe some functionality should be split into separate classes.
  • Within each class, are there many methods that seem too long, or are things split up nicely? Objective-C code is, by necessity, longer than the corresponding code would be in a language like Ruby, but generally shorter is better. Anything longer than ten or fifteen lines might be worth refactoring, and anything longer than 30 or 40 lines is almost definitely in need of refactoring.
  • Is the app compiled with ARC, MRR, or a mix? If not all ARC, why not?

Cocoa

  • Does the app make good use of common Cocoa patterns, such as MVC, notifications, KVO, lazy-loading, etc? Are there any efforts underway to adopt patterns that aren't backed by Apple, but are gaining steam in the iOS world, such as Reactive Cocoa and MVVM?
  • Are there view-controllers that are overloaded with too much responsibility?
  • If discrete sections of the app need to communicate with each other, how do they do so? There are multiple ways of accomplishing this (KVO, notifications, a big pile of global variables, etc), each with their own pros and cons.

Model Layer

  • If the app is using Core Data, does the data model seem sufficiently normalized and sensible? Is the Core Data stack set up for the possibility of doing some work on a background thread? See Theo's guide to core data concurrency for more on this.
  • If not using Core Data, does the app store data using some other techniques, and if so, does it seem reasonable?
  • At the other end of the spectrum, does the app skip model classes to a large extent, and just deal with things as dictionaries?

GUI

  • Is the GUI created primarily using xibs, storyboards, or code?
  • Is GUI layout done with constraints, the old springs'n'struts, or hard-coded frame layout?
  • Does the running app have a reasonable look and feel?

Network Layer

  • Is all networking done using asynchronous techniques, allowing the app to remain responsive?
  • If a 3rd-party network framework is being used, is it a modern, supported framework, or something that's become a dead end?
  • If no 3rd-party network framework is in use, are Apple's underlying classes being used in a good way? (There are plenty of ways to get this wrong).
  • Does the app function in a fluid manner, without undesireable timeouts or obvious network lags affecting the user?

Other

  • Is the app localized for multiple languages? If so, is this done using standard iOS localisation techniques?
  • If there are tricky/difficult things happening in the code, are these documented?

This is a pretty hefty set of things to consider. Depending on the code base, you won't necessarily be able to find a clear yes/no answer for all of these questions, and for certain types of apps, some of these points will be meaningless. Note that I'm not saying exactly what I think are the "right" answers for all of the questions listed here, although I certainly have my share of strong opinions about most of these (but those are topics for other blog posts). Even if you wouldn't agree with my answers, these are probably all points that are worth thinking about and discussing with co-workers and other collaborators to figure out just what seems right for your projects.

Episode #441 - February 18th, 2014

Posted about 1 month back at Ruby5

In this episode we cover mruby 1.0, Hound CI, ActiveIntegration, Rails Flash Partials, Inch, Inheritable Aliases, and a big Rails for Zombies update. Put down your brains and your entrails.

Listen to this episode on Ruby5

Sponsored by TopRubyJobs

If you're looking for a top Ruby job or for top Ruby talent, then you should check out Top Ruby Jobs. Top Ruby Jobs is a website dedicated to the best jobs available in the Ruby community.
This episode is sponsored by Top Ruby Jobs

mruby 1.0 Released!

Earlier this month mruby 1.0 was released. This is a lightweight implementation of the Ruby language which can be linked and embedded within an application. You can also compile Ruby programs into compiled byte code.
mruby 1.0 Released!

Hound CI

Scott Albertson from Thoughtbot just released Hound CI, which is a service that reviews GitHub pull requests for style guide violations. It provides guidelines for things like git workflow, code formatting, naming, organization, and language-specific conventions for languages like Sass, Ruby, Coffeescript, Objective-C, and Python. AND it even includes some Rails development conventions for HTML, routing, background jobs, and testing.
Hound CI

Confidently Manage Business Logic with ActiveInteraction

OrgSync recently released version 1.0 of their gem ActiveInteraction, which helps manage application specific business logic. It's a unique way to help you keep business logic out of your models and controllers.
Confidently Manage Business Logic with ActiveInteraction

Rails Flash Partials

Zack Siri from Codemy wrote to us about another screencast he’s created, this time it’s about Rails Flash Partials. Setting up flash messages in Rails is really simple, but it can become more complex as your application grows. Rails partials are great for keeping your code DRY, and flash messages are no exception.
Rails Flash Partials

Inch

So there’s lots of libraries to help you rate your code, based on complexity, code coverage and so on and so on.. But this week I found a library that will grade how well your code is documented called Inch, by René Föhring. Check it out next time you need to beef up your documentation on a project.
Inch

Inheritable Aliases in Ruby

Ruby’s method aliases are pretty handy, but if you method_alias in a class and then extend from that class, it won’t work. One way to solve this is by using the Forwardable module and its def_delegator method that are included in the Ruby standard library. However, a better solution is outlined in Nate Smith’s blog post, in which he describes writing a custom inheritable_alias method.
Inheritable Aliases in Ruby

Rails for Zombies Updated!

Over on Code School we just updated the original Rails for Zombies to be compatible with Rails 4 and Ruby 2. We made a massive improvement to the videos as well, so if you know anyone that needs to get started with Ruby on Rails, you know where to send em.
Rails for Zombies Updated!

Thank You for Listening to Ruby5

Ruby5 is released Tuesday and Friday mornings. To stay informed about and active with this podcast, we encourage you to do one of the following:

Thank You for Listening to Ruby5

Your Docker image might be broken without you knowing it

Posted about 1 month back at Phusion Corporate Blog

Docker is an awesome new technology for the creation of lightweight containers. It has many purposes and serves as a good building block for PaaS, application deployments, continuous integration systems and more. No wonder it’s becoming more and more popular every day.

However what a lot of people may not realize is that the operating system inside the container must be configured correctly, and that this is not easy to do. Unix has many strange corner cases that are hard to get right if you are not intimately familiar with the Unix system model. This can cause a lot of strange problems. In other words, your Docker image might be broken, without you knowing it.

To raise awareness about this problem, we’ve published a website which explains the problem in detail. It explains what exactly could be broken, why it’s broken that way, and what can be done to fix them.

And to make it easier for other Docker users to get things right, we’ve published a preconfigured image — baseimage-docker — which does get everything right. This potentially saves you a lot of time.

Learn the right way to build your Dockerfile.

One of the gripes we have with random Docker images on the Docker registry is that they’re often very poorly documented, and do not provide the original Dockerfile from which they’re created. With baseimage-docker, we’re breaking that tradition by providing excellent documentation and by making the entire build reproducible. The Dockerfile and all other sources are available at Github, for everyone to see and to modify.

Happy Docking!

Using Arel to Compose SQL Queries

Posted 2 months back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Rails gives us a great DSL for constructing most queries. With its knowledge of the relationships between our tables, it's able to construct join clauses with nothing more than the name of a table. It even aliases your tables automatically!

The method we most often reach for when querying the database is the where method. 80% of the time, your query will only be checking equality, which is what where handles. where is smart. It handles the obvious case:

where(foo: 'bar') # => WHERE foo = 'bar'

It also handles nils:

where(foo: nil) # => WHERE foo IS NULL

It handles arrays:

where(foo: ['bar', 'baz']) # => WHERE foo IN ('bar', 'baz')

It even handles arrays containing nil!

where(foo: ['bar', 'baz', nil]) # => (WHERE foo IN ('bar', 'baz') OR foo IS NULL)

With Rails 4, we can also query for inequality by using where.not. However, where has its limitations. It can only combine statements using AND. It doesn't provide a DSL for comparison operators other than = and <>.

When faced with a query that requires an OR statement, or when needing to do numeric comparisons such as <=, many Rails developers will reach for writing out a SQL string literal. However, there's a better way.

Arel

Arel is a library that was introduced in Rails 3 for use in constructing SQL queries. Every time you pass a hash to where, it goes through Arel eventually. Rails exposes this with a public API that we can hook into when we need to build a more complex query.

Let's look at an example:

class ProfileGroupMemberships < Struct.new(:user, :visitor)
  def groups
    @groups ||= user.groups.where("private = false OR id IN ?", visitor.group_ids)
  end
end

When we decide which groups to display on a users profile, we have the following restriction. The visitor may only see the group listed if the group is public, or if both users are members of the group. Even for a minor query like this, there's several reasons we would want to avoid using SQL string literals here.

  • Abstraction/Reuse
    • If we wanted to reuse any piece of this query, we would end up with a leaky abstraction at best involving string interpolation.
  • Readability
    • As complex SQL queries grow, they can quickly become difficult to reason about. Since they're so difficult to break apart, the reader often has to understand the entire query to understand any individual part.
  • Reliability
    • If we join to another table, our query will immediately break due to the ambiguity of the id column. Even if we qualify the columns with the table name, this will break as well if Rails decides to alias the table name.
  • Repetition
    • Often times we end up rewriting code that we already have as a scope on the class, just to be able to use it with an OR statement.

Refactoring to use Arel

The method Rails provides to access the underlying Arel interface is called arel_table. If you're working with another class's table, the code may become more readable if you assign a local variable or create a method to access the table.

def table
  Group.arel_table
end

The Arel::Table object acts like a hash which contains each column on the table. The columns given by Arel are a type of Node, which means it has several methods available on it to construct queries. You can find a list of most of the methods available on Nodes in the file predications.rb.

When breaking apart a query to use Arel, I find a good rule of thumb is to break out a method anywhere the word AND or OR is used, or when something is wrapped in parenthesis. Keeping this rule in mind, we end up with the following:

class ProfileGroupMemberships < Struct.new(:user, :visitor)
  def groups
    @groups ||= user.groups.where(public.or(shared_membership))
  end

  private

  def public
    table[:private].eq(false)
  end

  def shared_membership
    table[:id].in(visitor.group_ids)
  end

  def table
    Group.arel_table
  end
end

The resulting code is slightly more verbose due to Arel's interface, but we've given intention-revealing names to the underlying pieces, and are able to compose them in a satisfying fashion. The body of our public groups method now also describes the business logic we want, as opposed to how it is implemented.

With more complex queries, this can go a long way towards being able to easily reason about what a query is accomplishing, as well as debugging individual pieces. It also becomes possible to reuse pieces of scopes with OR clauses, or in the body of JOIN ON statements.

What's next?

  • Learn more about composition over inheritance in Ruby with Ruby Science

Senior Ruby on Rails developer. £50k Award winning company, prestigious country location, Oxfordshire near Reading/High Wycombe

Posted 2 months back at Ruby on Rails, London - The Blog by Dynamic50

Great opportunity for an experienced developer specialising in Ruby on Rails.

Prestigious countryside town location, Oxfordshire near Reading/High Wycombe

Working in close knit team directly with the CTO on award winning web application.

Opportunity to really contribute to an active product roadmap in an award winning small company. Really make a difference

- 3+ experience developing commercial web applications using Ruby on Rails, Python, Java, .NET, PHP or similar

- Passion for programming a must, daily stand-ups, etc.

- Knowledge of relational database design, SQL.

- Extensive experience with JavaScript, AJAX, CSS and HTML

- Experience with Agile methodologies

- Working knowledge of version control systems, SVN, Git.

- Experience with test driven development

- Knowledge of Eclipse would be an advantage

- Knowledge of Linux would be an advantage

Salary 50k

Send your resume to contactus@dynamic50.com or give us a call on 02032862879