joey beninghove

coder micropreneur

Octopress + Font Awesome

Permalink

For the past year or so I’ve been doing a lot of work with Bootstrap and recently with Gimlet, a Bootstrap theme for Rails. As part of this I’ve grown to love the awesome Font Awesome icons, so I decided to sprinkle them here on my Octopress blog. I think I like it! I love how easy it is to customize Octopress with my own flavors.

Oh and I updated my About and Work pages with some new stuff. :)

Grape APIs - Few Quick Tidbits

Permalink

It’s been pretty quiet here for a long time, but I’ve been busy building a few businesses, one of which includes a new product I’m helping to build and launch with a couple friends. One of the things I’ve been building is a robust REST API using Grape. If you want a quick overview, check out their README on the GitHub repo. I’ve really enjoyed using Grape and figured I’d share a few little tidbits of how I’m using it so far.

Configuring URL prefix

For a long time I was just using Rails 3 to “mount” my Grape API class like this:

routes.rb
1
mount MyApp::API => '/api'

This worked well for a while, but then I had a need to plug in some Rack middleware (such as Rack::Cors, which I plan to blog about soon). Long story short, I couldn’t mount it the same way anymore, but still needed to configure the base URL for the API to point to /api. Grape makes this really easy.

my_app_api.rb
1
2
3
4
5
module MyApp
  class API < Grape::API
    prefix 'api'
  end
end

Quick side note, I do still mount the API in the Rails routes for the test environment only for my automated API integration tests. But since I already have the prefix defined in the API, I just mount it to root for these purposes.

routes.rb
1
2
3
if Rails.env == 'test'
  mount MyApp::API => '/'
end

Delegate to the Rails logger (if desired)

my_app_api.rb
1
logger Rails.logger

Simple.

Request logging, including body

my_app_api.rb
1
2
3
4
5
before do
  # Of course this makes the request.body unavailable afterwards.
  # You can just use a helper method to store it away for later if needed. 
  Rails.logger.info "Request Body: #{request.body.read}"
end

Easy peasy.

Global exception handling

my_app_api.rb
1
2
3
4
5
6
7
8
9
10
rescue_from :all do |e|
  # Log it
  Rails.logger.error "#{e.message}\n\n#{e.backtrace.join("\n")}"

  # Notify external service of the error
  Airbrake.notify(e)

  # Send error and backtrace down to the client in the response body (only for internal/testing purposes of course)
  Rack::Response.new({ message: e.message, backtrace: e.backtrace }, 500, { 'Content-type' => 'application/json' }).finish
end

Handy.

HTTP Basic Authentication

my_app_api.rb
1
2
3
http_basic do |username, password|
  User.authenticate!(username, password)
end

No sweat.

Helper methods

my_app_api.rb
1
2
3
4
5
6
7
helpers do
  def current_context
    @context = # some call to retrieve context based on API key maybe?
  end

  # anything else needed by a group of or all resource/verb blocks
end

Straightforward.

Sending back errors with validation messages

my_app_api.rb
1
2
3
4
5
6
7
resource :turtles
  post do
    # make sure you filter/whilelist the request body attributes!
    turtle = Turtle.create(JSON.parse(request.body.read))
    error!(turtle.errors.messages, 400) unless turtle.valid?
  end
end

Smooth sailing.

General API building tips

I can’t recommend enough the article that John Nunemaker wrote recently on Creating an API. A great read with some great tips.

That’s all for now. Happy coding! :)

New Backbone.js on Rails Screencast - When Things Go Wrong!

Permalink

Another quick announcement about my latest Backbone.js screencast over at backbonescreencasts.com. This time it’s another one relating to Rails, When Things Go Wrong!. In this one I cover dealing with errors, specifically validation errors from Rails as well as monitoring server availability and reacting to server downtime.

Here’s a preview:

Interested?

Check out this one, as well as the special bundles available over at backbonescreencasts.com.

P.S. I have a LOT of cool stuff to blog about, which I hope to get to soon. :)

Rails 3.1, Asset Pipeline, Sass Syntax & Heroku

Permalink

I’m starting to build out my first Rails application on Heroku (cedar stack), ever. Yes, I know, I’m really late to the party. But I just ran across something that might be causing folks trouble if they’re attempting to deploy a Rails 3.1 application to Heroku and prefer the sass syntax over the default scss.

(First off I want to say thanks to Benjamin Atkin for giving me the idea for this fix in this blog post about Compass and Heroku.)

As much grief as I get over it, I am still an old school Sass guy and still prefer the sass syntax instead of the default scss that is shipped with Rails 3.1. Thankfully, this is quite easy to change in the Rails configuration as show here.

application.rb
1
2
# Prefer SASS, 'cause that's what real men use :)
config.sass.preferred_syntax = :sass

However, when you try to deploy this Heroku, the server fails to start. This can be discovered by running heroku logs.

from output of ‘heroku logs’
1
2
3
/app/vendor/bundle/ruby/1.9.1/gems/railties-3.1.0/lib/rails/railtie/configuration.rb:78:in 
`method_missing': undefined method `sass' for #<Rails::Application::Configuration:0x000000016152c8> 
(NoMethodError)

As pointed out in Benjamin’s post, this is because

…Heroku only runs with the asset gems from the Gemfile when it compiles the assets, and it only compiles the assets when a new slug is loaded.

So I took his idea and created a Sass initializer to handle the setting of this for me, only when a Sass configuration object is available.

config/initializers/sass.rb
1
2
3
4
5
6
if Rails.configuration.respond_to?(:sass)
  Rails.configuration.sass.tap do |config|
    # Prefer SASS, 'cause that's what real men use :)
    config.preferred_syntax = :sass
  end
end

UPDATE 10/02/2011

Just found out that the initializer above won’t actually get run when you run rails generate, which kind of defeats the purpose. So this code must be run from application.rb, either included directly or required.

By doing this, it allows the Heroku cedar stack to properly precompile the assets and successfully start the Rails server.

One other way to “fix” this issue is to move the sass-rails gem into the global group in your Gemfile. But I think I prefer the solution above so I don’t have to pollute the global gem group with an unnecessary gem just to satisfy Heroku deployment.

Happy coding!

Vim Macros - 5 Minute Screencast

Permalink

The other day as I was converting this blog over to Octopress, I recorded a short little screencast on how I was able to use Vim macros to make migrating my old blog posts a LOT easier. This was the result…

(HINT: Best watched in HD mode, full screen)

Don’t forget to sign up for CastingCode.tv to see more!

Coder Talk - Episode 3 - Javascript Inheritance, Pair Programming, VMs, Static Site Generators and More!

Permalink

Another long episode of Coder Talk is here, hosted by myself and Derick Bailey. This week we are joined by Joe Fiorini, Alan Audette, Nathan Palmer, Paul Yoder and Thomas Brewer. We discuss javascript inheritance, the joys of pair programming, which VM product can beat up the other VM product’s daddy and our love for static blogs including an interesting idea from Joe. We also heard a great success story from Paul on building a lean, profitable software product, DonorElf. Finally, we wrapped things up giving tons of love to one of our favorite products out there right now, KickoffLabs and talk about some of the projects we’re all working on.

Please let us know what you think by leaving a comment below. Enjoy!

Links From The Show