Three In A Tree

Posted 3 months back at Mike Clark

<iframe src="//player.vimeo.com/video/99295895?title=0&amp;byline=0&amp;portrait=0" width="700" height="394" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>

What's more fun than a black bear cub playing in a tree? Three black bear cubs playing in the same tree, of course! We really enjoyed watching these siblings explore their new world this spring.

GMDSP: Phase 2

Posted 3 months back at RicRoberts :

The Greater Manchester Data Synchronisation Programme project (which I first wrote about here) is entering a new phase after a successful first release of the data at the hack day held in late March.

As a brief background, the initial phase involved Manchester City Council, Salford City Council and Trafford Metropolitan Borough Council releasing open and linked datasets simultaneously. This allowed technical, and non-technical, users to access and use the data in a format that suits them.

The accompanying hackathon saw nine teams from across Europe develop some rather nifty prize-winning apps, including Light Raider (which won the Lifestyle and Wellbeing Challenge and has already recieved publicity). This app uses data about Manchester’s streetlights for a game where joggers compete with others to gain points each time they pass (raid) a street light.

So the next phase involves all ten district councils from the Greater Manchester area - this is a a brilliant example of how local authorities can embrace linked open data.

We’ll be continuing our collaboration with Future Everything on this project. They’re recruiting more code fellows to help model the data whilst we host it and provide training and consultancy. Check out gmdsp on twitter for more details of the next coding challenge to be held this summer.

Reducing risk when running a conference

Posted 3 months back at interblah.net - Home

It was really interesting to read the news about the potential cancellation of Wicked Good Ruby, a Ruby conference that was due to run for a second time in Boston this year:

Rather than half-ass a conference we’ve decided to cancel it. All tickets will be fully reimbursed. I’ve already reached out to those that have purchased with how that will be done.

There’s lots of interesting stuff in this thread, but one point that jumped out to me was the financial risk involved:

Zero sponsors. […] I had 2 companies inquire about sponsorship. One asked to sponsor but never paid the sponsorship invoice after 82 days.

[…]

Last year we lost $15k. In order to made it worth our effort this year we needed to make a profit. The conference we had in mind required a $50k sponsorship budget with an overall budget of close to $100k. (last year’s conference cost about $125k) Consider to date, after 6 months, we have received $0 in sponsorship the financial risk was too high.

[…]

Since announcing this a few hours ago I’ve been contacted by 3 other regional conference organizers. They are all having similar issues this year. Sponsorship is incredibly difficult to come by […] I didn’t get the sense they were going to bail but I think this is a larger issue than just Boston.

With costs in the tens or even hundreds of thousands of dollars, it’s really no wonder that organisers might have second thoughts.

But does running a conference really need to come with such an enormous financial risk? With Ruby Manor, our biggest budget was less than £2,000 (around $3,000). Here’s why:

  • We don’t use expensive ‘conference’ venues…
  • … so we aren’t locked into their expensive conference catering.
  • We run a single track for a single day, so we only need one main room.
  • We meticulously pare away other expenses like swag, t-shirts, catering and so on, where it’s clear that attendees are perfectly capable of handling those themselves.

Now, it could be that there are a few factors unique to Ruby Manor that make it difficult, or even impossible, for other conferences to follow the same model. For instance, holding the event in the center of a big city like London means there’s already a wide range of lunch options for attendees, right outside the venue.

Another problem could be the availability of university and community venues as an alternative to conference centres. I really don’t know if it’s possible or not to rent spaces like this in other cities or countries. A quick look at my local university indicates that it’s totally feasible to rent a 330-seat auditorium for less than $1,000, and even use their coffee/tea catering for a total of less than $3,0001, all-in.

I would be genuinely fascinated for other conferences to start publishing their costing breakdown. LessConf have already done this, and even though I might not have chosen to spend quite so much money on breakfasts and surprises, I genuinely do applaud their transparency for the benefit of the community.

In the end it seems there’s hope for Wicked Good:

I think I’ve come up with a plan: reduce the conference from 2 nights to 1 night. Cut out many of the thrills that I was planning. This effectively would reduce our operational costs from ~$100k to around ~$50k. This would also allow us to reduce the ticket prices (I would reimburse current tickets for the difference).

I genuinely wish the organisers the best of luck. It’s a tough gig, running a conference. That said, $50,000 is still an enormous amount of money, and I cannot help but feel that it’s still far higher than it needs to be.

Every hour you spend as a conference organiser worrying about sponsorships or ticket sales or other financial issues, is an hour that could be spent working on making the content and the community aspects as good as they can be.

Let’s not forget: the only really important part of a conference is getting a diverse group of people with shared interests into the same space for a day or two. Everything else is just decoration. A lot of the time, even the presentations are just decoration. It’s getting the community together that’s important.

I realise that many people expect, consciously or otherwise, some or all of the peripheral bells and whistles that surround the core conference experience. For some attendees, going to a conference might even be akin to a ‘vacation’ of sorts. Perhaps a conference without $15,000 parties feels like less of an event… less of an extravaganza.

But consider this: given the choice between a glitzy, dazzling extravaganza, and a solid conference that an organiser can run without paralysing fear of financial ruin, I know which I would choose, and I know which ultimately benefits the community more.

  1. To be clear, they require that you cannot make a profit on events they host, but from what I can tell, most conference organisers don’t wish to run their events for profit anyway.

Feels So Good

Posted 3 months back at Mike Clark

<iframe src="//player.vimeo.com/video/99084298?title=0&amp;byline=0&amp;portrait=0" width="700" height="393" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>

A few years back I filmed this beaver preening. She gave herself a good rub-a-dub-dub before slipping back into the den for a well-deserved nap.

Episode #475 - June 24th, 2014

Posted 3 months back at Ruby5

Mongoid 4.0.0, a CHANGELOG rant, the Lotus web framework, help on Growing Rails Applications in Practice, the upcoming Keep Ruby Weird conference, ConfConf for safer configuration, and the demise of RubyForge.

Listen to this episode on Ruby5

Sponsored by Codeship.io

Codeship is a hosted Continuous Deployment Service that just works.

Set up Continuous Integration in a few steps and automatically deploy when all your tests have passed. Integrate with GitHub and BitBucket and deploy to cloud services like Heroku and AWS, or your own servers.

Visit http://codeship.io/ruby5 and sign up for free. Use discount code RUBY5 for a 20% discount on any plan for 3 months.

Also check out the Codeship Blog!

Codeship

Mongoid 4.0.0

In Mongoid 4.0.0 field types can now use symbols as well as class names, fields can now be reset to their default values, documents now have a destroy! method that raises in case of destroy callback issues, Mongoid now uses ActiveSupport::LogSubscriber and ActiveSupport::Notifications, *and* there’s a lot more to read in the CHANGELOG including dozens of bug fixes. Since Mongoid follows semantic versioning, there are several backwards incompatible changes with the previous versions: it now only supports MongoDB 2.4.0, Document#metadata has been renamed to Document#relation_metadata, the Rails dependency on database rake tasks has been removed, and there are quite a few more you can find a beautifully detailed CHANGELOG.
Mongoid 4.0.0

Keep a CHANGELOG

Speaking lof CHANGELOGs, I want to encourage open source contributors who listen to us to provide a CHANGELOG as great as the one Mongoid provided for this new release. It’s important to present the new features, removed features, breaking changes and bug fixes in each version release. I’m a bit obsessed about this so I put up a little pamphlet called keepachangelog.com. Just remember: Friends don’t let friends dump git logs in CHANGELOGs.
Keep a CHANGELOG

Lotus

If Rails isn’t your cup of tea and Sinatra doesn’t strike, there’s a new Ruby web framework on the block. It’s called Lotus and was written by Luca Guidi who describes it as a complete web framework with a strong emphasis on object-oriented design and testability. It’s Rack compliant like them, which seems like good news. The focus seems to be on simplicity — with standalone frameworks: Lotus::Controller, Lotus::Router, Lotus::Model, Lotus::View, etc. For instance you can use Lotus::Router to dispatch HTTP request to a pool of Sinatra applications. Aside from this, Luca emphasizes plain objects, a minimal DSL, and stable APIs. Lotus::View, contrary to Rails, separates view objects and templates. Lotus::Model tries to keep domain-specific logic away from persistence logic. Luca describes the documentation as extensive and at a high level it seems quite thorough. Anybody curious about web frameworks should give it a look and potentially offer Luca some feedback and contributions.
Lotus

Growing Rails Applications in Practice

Thomas Eisenbarth wrote to us about a new book he’s co-written called Growing Rails Applications in Practice. Instead of advocating a big architectural rewrite, this book aims to provide actionable steps that every Rails developer can use -- like writing *beautiful* controllers, extracting service objects, organizing large codebases with namespacing, and much more. Ultimately, this book is about how to use discipline, consistency and organization to make your application grow more gently.
Growing Rails Applications in Practice

Keep Ruby Weird

Some of the Austin, Texas Ruby community has organized a new conference called Keep Ruby Weird. It’s a one-day conference filled with... weird. It also has a pretty sweet logo. I hope there will be stickers. They’re still in the planning phase, so the Call for Proposals is open. Head over to keeprubyweird.com to submit a talk or sign up for their mailing list and get more info as it’s announced.
Keep Ruby Weird

ConfConf

James Kassemi let us know about a very simple utility called ConfConf, which verifies the correctness of environment variables at application boot so you can fail fast when there's a configuration problem. After adding the gem to your Gemfile and bundling, you can just add an initializer for ConfConf that contains the environment variables you want to check for. If .. when booting your application, the environment variables are not present, a ConfConf::MissingConfigurationValueError is raised.
ConfConf

RubyForge Shut Down

Listener Željko Filipin reminded us that we never mentioned the fact that RubyForge was shut down May 15th. If you still relied on the site it might be a good time to do a cursory check and make sure you don’t depend on it anymore.
RubyForge Shut Down

Sponsored by Top Ruby Jobs

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.
Top Ruby Jobs

Sponsored by 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

Let me tell you a bit about what I'm doing

Posted 3 months back at interblah.net - Home

This irregularly-kept blog thing is getting so irregular it’s almost regularly irregular. Lest you fool yourself into presuming any ability to predict when I might write here (i.e. “never”), let me thwart your erroneous notion by serving up this rambling missive, unexpected and with neither warning nor warrant!

Take that, predictability! Chalk another one up for chaos.

I live in Austin now, or at least, for the moment

In summer last year, I moved from London to Austin. My other half had already been living in Austin for two years, and I’d been flying back and forth ever other month or so, but 24 months of that is quite enough, and so I bit the bullet and gave up my London life for Stetsons and spurs. It’s been quite an adventure so far, although I do miss a few people back in the UK.

We don’t know how long we’ll stay here, but for the moment I’m enjoying the weather immensely. You might think it’s a balmy summer in London when temperatures regularly reach 20°C, but during Austin’s summer the temperature never drops below 20°C, even at night. Can you even conceive of that?

Farewell Go Free Range, Howdy Exciting

Leaving the UK also marked the beginning of the end of the Free Range experiment for me. Ever since I started kicking the ideas for Free Range around in late 2008, I’ve always considered it an experiment. I wish I could say that it had been a complete success, and it was very successful in a number of important ways, but if you’re going to pour a lot of energy into trying to make something for yourself, it really needs to be moving in the direction you feel is valuable.

I wrote a bit more on the Exciting blog and the Free Range blog. I could say a lot more about this – indeed, I have actually written thousands of words in various notepads and emails – but I’ll save that for another time; my memoirs, maybe. It takes a lot of effort to keep a small boat moving in a consistent direction through uncharted waters.

So: I’ve spun out a lot of the projects I was driving into a new umbrella-thing called Exciting, and that’s the place to look at what I’m working on.

Right, but what are you doing exactly?

Well, I’m still doing the occasional bit of client work, and I have some tinkering projects that I need to write more about, but this year I have mostly been1 working on Harmonia. Although it was built for Free Range, it’s still both a product and a way of working that I believe lots of teams and companies could benefit from. I’ve added a fair bit of new functionality (more calendar and email functionality, webhooks, Trello integration) and fixed a whole bunch of usability issues, the lion’s share of the work has been in working on how to communicate what Harmonia does and how it could help you.

I really cannot overstate the amount of effort this takes. It’s exhausting. Some of that is doubtless because I am a developer by training, and so I’ve had to learn about design, user experience, copywriting, marketing, and everything in between, as I’ve gone along. It’s very much out of my comfort zone, but it’s simply not possible to succeed without them.

You can build the best product in the world, but if nobody knows it exists or can quickly determine whether or not it’s something they want… nobody will ever use it.

The good thing is that the web is the ideal medium for learning all this, because you can do it iteratively. I’ve completely redesigned the Harmonia landing page four times since it became my main focus, and each time I think it’s getting better at showcasing the benefits that it can bring. It still needs more work though; as of writing this I think it’s too wordy and the next revision will pare it down quite a bit.

Going solo

It’s also a real challenge to keep up this effort while working alone. It’s hard to wrangle a group of people into a coherent effort, but once you succeed then it provides a great support structure to keep motivation up and to share and develop ideas. Working by yourself, you don’t have to deal with anyone else’s whims or quirks, but you also only have yourself to provide motivation and reassurance that what you’re working on is valuable, and that the decisions you’re making are sensible.

What’s more, it can be challenging to stay motivated in a world seemingly filled by super-confident, naturally-outgoing entrepreneur types. I don’t operate with the unshakable confidence that what I’m building is awesome, or that my ideas are worth sharing, or that they even have any particular merit.

Confronted with the boundless crowd of what-seems-typical Type A entrepreneurs that fill the internet, prolifically, with their reckons and newsletters and podcasts and blog posts and courses, I often wonder about the simpler life of just being an employee; of offloading the risk onto someone else in exchange for a steady incoming and significantly less crippling self-doubt. I’m sure I’m not the only person who feels this way, whose skin crawls as yet another service or blog post or person is cheaply ascribed the accolade “awesome” when really, I mean, really, is it? Is it?

But… there’s still a chance that I might be able to carve out a niche of my own, and maybe build another little company of friends working on small things that we care about, and investing in our future collectively. I still believe that’s a possibility.

Anyway, so that’s what I’m doing, mostly: crushing it.

  1. Couldn’t resist this turn of phrase; see here if you don’t immediately get it.

Introducing Lotus

Posted 3 months back at Luca Guidi - Home

A year and a half ago I felt frustrated by the state of the art of web development with Ruby. Secretly, in my spare time, I started hacking with new ideas, taking nothing for granted, destroying and starting from scratch several times, until the software was distilled in a beautiful API.

It took me a decade to get here, by following a process of subtraction of what isn’t essential. Countless refinements to achieve modularity, to balance elegance with performance, and convenience with solid design.

Each alternative was ponderated according to real world scenarios. Use cases that have been pain points or good choices in my and other developers’ experience.

But this project was sitting on my computer for too long.

For this reason, at the beginning of the year, I announced the project and a slow release schedule. Each month I’ve released a library because I wanted to share with other developers the result of this effort, and create a discussion in the Ruby community. Now, six monhts and six frameworks later, I’m proud to introduce the main element: Lotus.

It’s a complete web framework, with a strong emphasis on object oriented design and testability. If you use Lotus, you employ less DSLs and more objects, zero monkey-patching, separation of concerns between MVC layers. Each library is designed to be small (under 500LOCs), fast and testable.

There is Lotus::Router which is an HTTP router and Lotus::Controller for controllers and actions. They both speak the Rack protocol, so they can be used in existing code base, or combined together for small API endpoint, or, again together, in a full stack Lotus app.

Lotus::View is the first library for Ruby that marks a separation between view objects and templates. While Lotus::Model, with repositories, data mapper and adapters helps to keep domain specific logic away from persistence.

We have infinite combinations. Small components have enormous advantadges in terms of reusability.

The power of these frameworks is combined together in Lotus applications.

Microservices are at the core. Several independent applications can live together in the same Ruby process.

Lotus has a smart mechanism of framework duplication, where all the libraries can be employed several times. As the code base grows up it can be easily split in smaller deliverables.

Lotus has an extensive documentation, that covers all the supported architectures.

The future

Lotus is still a young framework, that needs to reach a certain degree of code maturity. Alongside with the vision that I have for the future features, it will improved by collecting feedbacks from real world applications.

Also, starting from today, I’ll offer free consultancy hours to all the companies and individuals who are interested in Lotus.

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"/>


Episode #474 - June 20th, 2014

Posted 3 months back at Ruby5

Vic's Ember and Rails tutorial, gemoji, automatic exception googling, dev banners, Grand Central Dispatch, and an awesome laptop dev setup all in this episode of the Ruby5!

Listen to this episode on Ruby5

Sponsored by New Relic

New Relic is _the_ all-in-one web performance analytics product. It lets you manage and monitor web application performance, from the browser down to the line of code. With Real User Monitoring, New Relic users can see browser response times by geographical location of the user, or by browser type.
This episode is sponsored by New Relic

Vic Ramon's Ember Tutorial

Wondering how to build an app that tightly integrates Rails and Ember? Wondering how you might be able to use Ember even better? Read through Vic Ramon's Ember Tutorial for all this and more!
Vic Ramon's Ember Tutorial

gemoji

Looking for an easy way to get emoji all up in your Rails app? The gemoji gem's got you covered!
gemoji

stack_rescue

The stack_rescue gem will automatically run searches for runtime exceptions in your app.
stack_rescue

rack-dev-mark

The rack-dev-mark gem will throw a banner on your non-production environments so you'll never be confused again!
rack-dev-mark

Grand Central Dispatch

This blog post from MotionInMotion will show you how to better leverage Grand Central Dispatch in your RubyMotion apps.
Grand Central Dispatch

Laptop

Is your development environment a little lacking in the awesome department? The fine folks at thoughtbot just published a new open source project that automates the setup of your dev workstation.
Laptop

Laptop Setup for an Awesome Development Environment

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

We’ve published guides in 2009, 2011, and 2012 for setting up your Mac OS X laptop as a Ruby on Rails development machine. Many others have published and shared similar tutorials.

Instead of copying and pasting a series of steps from a blog post, a better approach is to leverage automation and the open source community to save time and get a more stable result.

For the past three years, we’ve been developing and maintaining Laptop, a shell script which turns a Linux or Mac OS X laptop into an awesome development machine.

Mac OS X

After setting up the prerequisites described in the project’s README, we run one line:

bash <(curl -s https://raw.githubusercontent.com/thoughtbot/laptop/master/mac)

Linux

There are no prerequisites for Linux except that we must use a supported version of Ubuntu (currently Trusty Tahy, Saucy Salamander, and Precise Pangolin), Debian stable (currently Wheezy), or Debian testing (currently Jessie).

Given a supported version, it is also one line to set up a Linux machine:

bash <(wget -qO- https://raw.githubusercontent.com/thoughtbot/laptop/master/linux)

How it works

Either script should take less than 15 minutes to install (depends on the machine).

The linux and mac scripts are short. They are intended to be human-readable so that we know exactly what is installed and idempotent in case an error requires the script to be run two or more times.

What it sets up

Laptop currently sets up these common components:

  • Zsh for the Unix shell
  • A systems package manager (Aptitude or Homebrew)
  • A Ruby version manager (rbenv)
  • A Ruby installer (ruby-build)
  • The latest stable version of Ruby
  • A Ruby package manager (Bundler)
  • A JavaScript package manager (NPM)
  • Our most commonly-needed databases (Postgres and Redis)
  • ImageMagick for cropping and resizing images
  • Qt for headless JavaScript testing via Capybara Webkit
  • A fuzzy finder (The Silver Searcher)
  • A terminal multiplexer (tmux)
  • A dotfile manager (rcm)
  • CLIs for interacting with GitHub and Heroku

Extending the script

Individuals can add their own customizations in ~/.laptop.local. An example ~/.laptop.local might look like this:

#!/bin/sh

brew tap caskroom/cask
brew install brew-cask

brew cask install dropbox
brew cask install google-chrome
brew cask install rdio

The ~/.laptop.local script can take advantage of the preparation the Laptop script does, such as its shared functions and exit trap, to provide better script output and aid debugging.

Vagrant boxes

We publish Vagrant boxes for each supported Linux distribution. These boxes have the Laptop script applied and ready to run. Setup looks like this:

vagrant init thoughtbot/ubuntu-14-04-server-with-laptop
vagrant up
vagrant ssh

We currently supply these Vagrant Cloud boxes:

thoughtbot/debian-wheezy-64-with-laptop
thoughtbot/debian-jessie-64-with-laptop
thoughtbot/ubuntu-14-04-server-with-laptop
thoughtbot/ubuntu-13-10-server-with-laptop
thoughtbot/ubuntu-12-04-server-with-laptop

Vagrant >= 1.5.0 is required to use Vagrant Cloud images directly.

What’s next?

After using Laptop to set up a development machine, a great next step is to use thoughtbot/dotfiles to configure Vim, Zsh, Git, and Tmux with well-tested settings that we’ve evolved since 2011.

Our dotfiles use the same ~/*.local convention as the Laptop script in order to manage team and personal dotfiles together with rcm.

Episode #473 - June 17th, 2014

Posted 3 months back at Ruby5

Nate and Gregg are back at it again, talking about a new release of Bundler, AREL, a new app with Ruby Shoes, attr_searchable, a passenger screencast, and SmartListing.

Listen to this episode on Ruby5

Sponsored by Codeship.io

Codeship is a hosted Continuous Deployment Service that just works.

Set up Continuous Integration in a few steps and automatically deploy when all your tests have passed. Integrate with GitHub and BitBucket and deploy to cloud services like Heroku and AWS, or your own servers.

Visit http://codeship.io/ruby5 and sign up for free. Use discount code RUBY5 for a 20% discount on any plan for 3 months.

Codeship

Bundler 1.6.3 has been released

Bundler 1.6.3 was released yesterday with a few new features and bug fixes. As of Bundler 1.6, Bundler now allows you to store private gem source URLs outside of your Gemfile using a bundle config source-url command. But, unfortunately, the Gemfile.lock still stored the secret keys. That’s now been fixed.
Bundler 1.6.3 has been released

The Definitive Guide to AREL the SQL Manager

Jiri Pospisil wrote up an amazing guide to AREL the SQL Manager, showing how you might use AREL separately from ActiveRecord to create sql statements. If you want to know what's going on under the covers, this is where to get started.
The Definitive Guide to AREL the SQL Manager

How to create post-it notes app in Ruby Shoes

Milos Dolobac put together an article detailing how to create a Post-It Note application using Ruby Shoes. Shoes is the Ruby GUI framework originally created by Why-the-lucky-stiff that is Mac, Windows, and Linux compatible.
How to create post-it notes app in Ruby Shoes

attr_searchable

The attr_searchable gem by Benjamin Vetter allows you to send ActiveRecord full text search queries, which it will parse and generate the proper SQL with AREL. Right now just PostgreSQL and MySQL are supported.
attr_searchable

Phusion Passenger Code Walkthrough

Hongli Lai recently created a 30 minute free video he put together giving you a walkthrough of the Phusion Passenger codebase. In the video he starts by giving an architectural overview, then dives into the code for initialization, request handling, process management, and application spawning.
Phusion Passenger Code Walkthrough

SmartListing

At some point if you’re building Rails applications you’ll inevitably need to build smart tables, that do things like AJAX pagination, sorting, filtering, and maybe even in-place editing. The SmartListing gem from the guys Sology which gives you all this functionality and more.
SmartListing

Sponsored by TopRubyJobs

Just two jobs on the top ruby job board this week. Braintree is looking for a Software Engineer in San Francisco, CA. phishme is looking for a mid Rails Developer in Chantilly, VA or remote
TopRubyJobs

Foolproof I18n Setup in Rails

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

Let’s make I18n on Rails better, quickly and easily. These tips have helped us here at thoughtbot and caught some easy-to-fix but hard-to-track-down mistakes.

Raise an exception on missing translations

When a translation is missing, Rails will fall back to a default translation. For example the code t(:hello) will output "hello" if there is no provided translation for :hello. This is almost certainly not what you want, especially for more complicated I18n keys like t('users.sign_in').

Most versions of Rails include a way to raise exceptions when a translation is missing. Raising an exception ensures that all of your calls to t() are using your copy, instead of using a default string. I recommend raising exceptions in the test and development environments, so that you can find missing translations by running tests and by browing around on localhost.

To raise exceptions on missing translations in Rails 4.1.0 and higher:

# config/environments/test.rb
# and
# config/environments/development.rb
Rails.application.configure do |config|
  config.action_view.raise_on_missing_translations = true
end

And in Rails 3:

# config/initializers/i18n.rb
if Rails.env.development? || Rails.env.test?
  I18n.exception_handler = lambda do |exception, locale, key, options|
    raise "Missing translation: #{key}"
  end
end

If you’re using a version of Rails 4 between 4.0.0 and 4.1.0, it requires a monkey patch, from Henrik Nyh:

# config/initializers/i18n.rb
if Rails.env.test? || Rails.env.development?
  module ActionView::Helpers::TranslationHelper
    def t_with_raise(*args)
      value = t_without_raise(*args)

      if value.to_s.match(/title="translation missing: (.+)"/)
        raise "Translation missing: #{$1}"
      else
        value
      end
    end
    alias_method :translate_with_raise, :t_with_raise

    alias_method_chain :t, :raise
    alias_method_chain :translate, :raise
  end
end

Time’s a-Wasting

Using I18n.t in tests is more typing than you really need. Here’s how you can use t() instead of I18n.t() in all of your tests:

RSpec.configure do |config|
  config.include AbstractController::Translation
end

Excellent.

What’s next?

Read about better tests through internationalization. You can also use the i18n-tasks gem to find and manage missing and unused translations in your application.

Announcing new, revamped developer documentation

Posted 3 months back at Phusion Corporate Blog

phusion_banner

We are excited to announce a set of new, revamped developer documentation for Phusion Passenger. While we’ve always had detailed user documentation, our developer documentation was quite sparse in comparison. We had a Contributors Guide that briefly shows you around, an Architectural Overview that mostly covers the I/O model and spawning system, and code comments. Despite this, it was hard for new developers to understand how things work.

Today, we’re changing this with the following:

  • The Contributors Guide has been much improved. It provides a clear, concise starting point for contributors.
  • The 8-minutes Developer Quickstart video shows you how you can get started with developing Passenger, through our Vagrant-based development environment. For those who don’t want to watch the video, there is also a Developer Quickstart document.
  • The Design and Architecture document explains in detail what the design and architecture looks like. It supersedes the Architectural Overview.
  • The Code Walkthrough video walks you through the Passenger codebase, showing you step-by-step how things fit together. It complements the Design and Architecture document.
Code Walkthrough

We need your feedback

At its heart, Passenger is and remains open source, and that means it’s important that people can easily understand and modify the code. We hope that with this, it is now significantly easier to contribute to Passenger. But is it easy enough now? Is there anything we should change or add? We don’t know.

Read the documents. Watch the videos. Use the comment box below and let us know what you think. :)

The post Announcing new, revamped developer documentation appeared first on Phusion Corporate Blog.

Announcing new, revamped developer documentation

Posted 3 months back at Phusion Corporate Blog

phusion_banner

We are excited to announce a set of new, revamped developer documentation for Phusion Passenger. While we’ve always had detailed user documentation, our developer documentation was quite sparse in comparison. We had a Contributors Guide that briefly shows you around, an Architectural Overview that mostly covers the I/O model and spawning system, and code comments. Despite this, it was hard for new developers to understand how things work.

Today, we’re changing this with the following:

  • The Contributors Guide has been much improved. It provides a clear, concise starting point for contributors.
  • The 8-minutes Developer Quickstart video shows you how you can get started with developing Passenger, through our Vagrant-based development environment. For those who don’t want to watch the video, there is also a Developer Quickstart document.
  • The Design and Architecture document explains in detail what the design and architecture looks like. It supersedes the Architectural Overview.
  • The Code Walkthrough video walks you through the Passenger codebase, showing you step-by-step how things fit together. It complements the Design and Architecture document.
Code Walkthrough

We need your feedback

At its heart, Passenger is and remains open source, and that means it’s important that people can easily understand and modify the code. We hope that with this, it is now significantly easier to contribute to Passenger. But is it easy enough now? Is there anything we should change or add? We don’t know.

Read the documents. Watch the videos. Use the comment box below and let us know what you think. :)

The post Announcing new, revamped developer documentation appeared first on Phusion Corporate Blog.

How Rails' Type Casting Works

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

Have you ever noticed that when you assign a property to an Active Record model and read it back, the value isn’t always the same? Here’s an example:

class StoreListing < ActiveRecord::Base
  connection.create_table :store_listings, force: true do |t|
    t.integer :price_in_cents
  end
end

store_listing = StoreListing.new
store_listing.price_in_cents = "100" # Note, this is a string
store_listing.price_in_cents # => 100

This is because Active Record automatically type casts all input so that it matches the database schema. Depending on the type, this may be incredibly simple, or extremely complex. Let’s take a look into how the internals work in 4.1.

The first method we need to understand in the above code is where the price_in_cents method is defined. In older versions of Rails, your models would go look up the database schema and define the attribute methods as soon as it was loaded. However, this caused problems on platforms like Heroku, where you might want to load the application when you don’t have a real database connection.

Today, the loading is lazy, and happens in a call to method_missing (source). The important line here is the call to define_attribute_methods.

def method_missing(method, *args, &block) # :nodoc:
  self.class.define_attribute_methods
  if respond_to_without_attributes?(method)
    # make sure to invoke the correct attribute method, as we might have gotten here via a `super`
    # call in a overwritten attribute method
    if attribute_method = self.class.find_generated_attribute_method(method)
      # this is probably horribly slow, but should only happen at most once for a given AR class
      attribute_method.bind(self).call(*args, &block)
    else
      return super unless respond_to_missing?(method, true)
      send(method, *args, &block)
    end
  else
    super
  end
end

Active Record’s definition of define_attribute_methods does little of note, other than call super with column_names (source).

def define_attribute_methods # :nodoc:
  return false if @attribute_methods_generated
  # Use a mutex; we don't want two thread simultaneously trying to define
  # attribute methods.
  generated_attribute_methods.synchronize do
    return false if @attribute_methods_generated
    superclass.define_attribute_methods unless self == base_class
    super(column_names)
    @attribute_methods_generated = true
  end
  true
end

We won’t look into how column_names gets determined today, but that method call is what causes Rails to go perform the SQL query that loads information about the model’s schema. Inside of Active Model, we’ll do some metaprogramming magic and ultimately end up calling define_method_attribute (source). Finally, in the body of define_method_attribute, we can see the method that gets called is read_attribute (source). Quite a bit of legwork!

If you decide to read along with us, make sure you’re on the 4-1-stable branch. A lot of this code has changed significantly on master. One of the most important changes to keep in mind is that @attributes_cache has been renamed to @attributes, and @attributes has been renamed to @raw_attributes.

The body of read_attribute looks like this:

def read_attribute(attr_name)
  # If it's cached, just return it
  # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
  name = attr_name.to_s
  @attributes_cache[name] || @attributes_cache.fetch(name) {
    column = @column_types_override[name] if @column_types_override
    column ||= @column_types[name]

    return @attributes.fetch(name) {
      if name == 'id' && self.class.primary_key != name
        read_attribute(self.class.primary_key)
      end
    } unless column

    value = @attributes.fetch(name) {
      return block_given? ? yield(name) : nil
    }

    if self.class.cache_attribute?(name)
      @attributes_cache[name] = column.type_cast(value)
    else
      column.type_cast value
    end
  }
end

Let’s go through each segment and understand what it’s doing. First we call to_s on the argument, as it’s possible we were passed a symbol (this method is part of the public API). Next we check to see if we’ve already type cast this attribute, as we cache the results. The next line is not always obvious.

column = @column_types_override[name] if @column_types_override
column ||= @column_types[name]

@column_types_override is sometimes given to us when the model in question was built as part of the result of a SQL query. If you’ve done something like

Post
  .joins(:comments)
  .select('posts.*, COUNT(comments.*) AS comments_count')
  .group('comments.post_id')

then we sometimes have to do additional leg work to type cast the count to an integer. If you ran that code while using the MySQL adapter or PostgreSQL adapter (keep in mind that most MySQL users are using the MySQL2 adapter), then @column_types_override would look like: { 'comments_count' => an_object_that_type_casts_to_int }. Continuing to the next line, @column_types will contain the column object that is crucial to this behavior, except for a few special cases (which we will have to cover another time).

The next block of code causes model.id to return the primary key, even if the primary key for the table is a column other than id.

return @attributes.fetch(name) {
  if name == 'id' && self.class.primary_key != name
    read_attribute(self.class.primary_key)
  end
} unless column

Next we need to grab the raw, un-typecast version of the attribute, which came either from user input, or from the database (“user” in this case refers to you, the programmer using Rails). However, there’s an interesting fork in behavior here.

value = @attributes.fetch(name) {
  return block_given? ? yield(name) : nil
}

The first question is whether or not a block was given. This is based on how read_attribute ended up being called. If you called it as post.title, no block would have been given. If you called it as post[:title], then a block would have been given to raise an exception. The reason that the title method would exist in this case, even if we don’t have a 'title' key in our attributes hash is: you performed a custom select statement. (This is an excellent example of how one feature can cause a surprising amount of complexity if not sufficiently isolated).

The conditional around caching attributes is actually bugged, and will always return true for most users, so we’ll ignore it. This leaves us with the line of importance:

@attributes_cache[name] = column.type_cast(value)

column in this case, will be an instance of ActiveRecord::ConnectionAdapters::Column, or one of its adapter specific subclasses. The behavior in question lives on the type_cast method (source).

# Casts value (which is a String) to an appropriate instance.
def type_cast(value)
  return nil if value.nil?
  return coder.load(value) if encoded?

  klass = self.class

  case type
  when :string, :text        then value
  when :integer              then klass.value_to_integer(value)
  when :float                then value.to_f
  when :decimal              then klass.value_to_decimal(value)
  when :datetime, :timestamp then klass.string_to_time(value)
  when :time                 then klass.string_to_dummy_time(value)
  when :date                 then klass.value_to_date(value)
  when :binary               then klass.binary_to_string(value)
  when :boolean              then klass.value_to_boolean(value)
  else value
  end
end

As any good method should, we start with an extremely misleading comment (the value will be anything you passed to the writer, not a string). Like many methods in Column, we also have a case statement based on type, and will call one of many helper methods based on which type it is. type will have been set back in the constructor, by using a regex from the sql_type source. sql_type will be the raw type string from the database schema, such as varchar(255).

At this point, the behavior is linear. All of the helper methods called exist in the class, and most are no more than a few lines long.

Also of note is the method type_cast_for_write, which gets called during the writer, before we store the attributes for type casting later. (Note: Anything that happens in this method will be applied to the _before_type_cast version of the attribute as well.)

If you’ve been cringing looking through the Column class, you’re justified. Luckily, it’s gotten much better. In preparation for adding a public API to hook into the type casting behavior in 4.2, this class has been heavily refactored to focus on polymorphism, rather than conditionals and regular expressions. In part 2, we’ll dig into some of the refactoring that’s been done, and the decisions behind it.

What’s Next?

Does your code base resemble the code we looked at today? Learn about common smells and refactorings with Ruby Science.

Episode #472 - June 13th, 2014

Posted 3 months back at Ruby5

5 Reasons why you'll Love Swift and doing gooder with ruby

Listen to this episode on Ruby5

Sponsored by surviving the Switch from Startup to Enterprise Dev

surviving the Switch from Startup to Enterprise Dev
NewRelic

5 Reasons Why Rubyist Will Love Swift

On tuesday ruby5 discussed why RubyMotion will not die anytime soon and not be replaced by swift, but today we have 5 Reasons Why Rubyists Will Love Swift
5 Reasons Why Rubyist Will Love Swift

Add Some Jazz to Your Rails App

why are you doing jazz hands, I'm talking about Jazz Hands, it makes your console jazzy
Add Some Jazz to Your Rails App

Business gem

Have you ever wanted to calculate dates based on the number of business days?
Business gem

Invoker 1.2

Invoker is a replacement for pow and foreman, but it also handles https
Invoker 1.2

Ruby for Good

RUBY FOR GOOD is a 3 day hackathon and workships to do help make the world a better place with Ruby
Ruby for Good