Blog Archives

Introducing Has Face for Rails

Posted in Code, Ruby on Rails, Tips and Tricks

Have you ever created an application where users are trusted to upload their own avatars? Wouldn’t it be great if there was an easy way to ensure the avatar contains a person’s face?

Has Face is a neat little gem that uses the face.com API to ensure that an image contains a persons face. It’s very simple to use and can be easily integrated into an existing rails application.

To get started add the has_face gem to your Gemfile and run a bundle install

Can’t see this Gist? View it on Github!

Run the generator to copy over an initializer:

Can’t see this Gist? View it on Github!

The initializer should look something like this:

Can’t see this Gist? View it on Github!

Now we’ll need to make a face.com developer account. You can signup for a free account over at face.com. Once you have signed up, place your API key and API secret in the initializer config.

The last option in the initializer (skip_validation_on_error) will change the behavior of has_face when an error occurs. If set to true, when an error occurs a warning will be logged to the logfile with detailed information about the failure and face validation will be skipped. This can be useful if you want your application to function if the API service is not reachable. If the value is false then an exception will be raised when an API call fails, this will allow you to manually handle the exception yourself, please check the documentation for details on the errors raised.

Once the initializer settings are setup then we can add face validation to a model. In the example below I’m using carrierwave to attach the image to the model but other image attachment gems should also work fine (anything that correctly responds to `path` should be OK).

Can’t see this Gist? View it on Github!

That’s it, that’s all we need to have a functioning face validator. There are a few other options that I haven’t covered here in this short guide, please consult the readme for more detailed information.

Simple Database Export and Import With Character Encoding Conversion

Posted in Code, Ruby on Rails

There is a gem called ydd that offers really simple import and export of smallish databases. It exports to YAML and then imports to whatever database Rails can connect to. After using YDD a few times I’ve found it easier to pinpoint the cause of problems that occur using taps.

It doesn’t handle character encodings though so I went about adding that. With the handy rchardet gem and IConv, detecting the character encoding of the incoming string and converting it to UTF-8 was pretty simple. I’ve created a pull request for the gem that will hopefully be accepted.

The essential code is below, and revolves mainly around the detection and conversion. Using //TRANSLIT causes IConv to try and convert the incoming character code to something that exists in the UTF8 character set, and then //IGNORE will ignore any characters that don’t exist in the UTF8 character set. Chaining //TRANSLIT and then //IGNORE will make IConv try a conversion first and then ignore anything it cannot convert.

I used this gem after the above changes to convert about 400,000 records of text data with ASCII, windows-1252, IBM866 and other character encodings from an old SQLite installation to a new postgres database without any issues.

Sending Apple Push notifications in rails with Redis and apn_sender

Posted in Code, Featured, Inside TFG, Ruby on Rails, Tips and Tricks

Sending iOS push notifications from a Rails application is very easy to do these days, thankfully there are many great Ruby gems that can be used to handle most of the magic for you. Recently I ran into the apn_sender gem which handles sending push notifications in a really neat way.

Sending push notifications directly from a Rails application can be slow and we probably don’t want to have the user waiting until the notification is sent, instead apn_sender can be setup to run a worker which is constantly connected to the apple push notification service. When there are new notifications to send, the notifications are queued up and sent through the always open connection that is maintained by the worker.

apn_sender uses redis as a message queue to keep track of the notifications waiting to be sent, you’ll need to install it before using the gem.

To add apn_sender in your Rails 3 application, just add the gem to your Gemfile. We’re going to need the daemons gem too so we’ll include that as well.

Can’t see this Gist? View it on Github!

Now we can create our daemon which we will be using for sending push notifications, this can be placed anywhere, I’ve put mine in script/apn_sender. Make sure to add execute permission to the file after creating so we can run it.

Can’t see this Gist? View it on Github!

Before the daemon can start running we’ll need to put our iOS push certificate into the application. Instructions for generating the certificates are available at the Apple Developer site. The certificates need to be placed inside of /config/certs and should be named apn_development.pem or apn_production.pem for production.

Once the certificates are in their correct locations, we can start up the daemon. The daemon does not know about the Rails environment so we need to specify this when starting it up. The daemon supports start, stop and restart commands. There is a verbose flag available to output more information (which can be helpful when debugging).

Can’t see this Gist? View it on Github!

Our application is now set up to send push notifications, this can now easily be performed by adding a new notification to the queue. The notify method on the APN class will take a push notification token and then our parameters, we can specify the alert message to show the user, whether or not we want sound as well as the number to display on the badge icon. Anything else we pass to notify will be sent as metadata in the push notification. Here’s an example of creating a notification.

Can’t see this Gist? View it on Github!

The worker should pick up the notification within a few seconds and send it off. The apn_sender has many other features that I haven’t covered, you can view the full documentation over at https://github.com/kdonovan/apn_sender.

Allowing Multiple Users to Use The Pivotal Tracker Gem

Posted in Code, Tips and Tricks

I’ve been using the Pivotal Tracker gem by Justin Smestad on a project to do various things but I ran into a problem using it with multiple API keys. The gem would create a single connection object and continue to mimic the user the first connection was made with, even when you’d updated the token to different user’s token. The Tracker API relies on you passing your API key for access to the projects and stories your account has access to, so I had the problem that the first user to use my app would determin access for everyone using the app. Not good!

After checking out the project the change was pretty simple but it highlighted an issue that I’ve seen in plenty of code where caching is done too broadly. In this case the cacheing (or memoization) was performed without taking into account the variable that was sent to establish the connection in the first place. The offending method looked like this :

Can’t see this Gist? View it on Github!

This was set on the class and as such @connection would never be created after the first call, whether the token was reset or not. I just changed it so that the connection is cached for each @token the system uses. For us it’s a small number or users, but in a larger context of course you’d need to implement some invalidation protocols to stop the following code from (slowly) swallowing the world :

Can’t see this Gist? View it on Github!

NoToken is just a class inheriting from StandardError that I chucked in there, the only thing that makes the gem now work properly come afterwards. I setup a hash and then store a new connection for each new incoming token, the connection is keyed by the token in the @connections hash. All pretty simple.

I’ve created a pull request that will hopefully be accepted soon, I think it fixes an unexpected problem with the gem.

Accessing ActiveRecord and ActiveModel Callback Chains in Rails 3

Posted in Code, Ruby on Rails, Tips and Tricks

It seems that access to the ActiveRecord callback chain has changed recently, however the documentation still contains the following :

To list the methods and procs registered with a particular callback, append _callback_chain to the callback name that you wish to list and send that to your class from the Rails console.

This used to work in Rails 2.3.x and I’d used it a few times before, however trying to use it in Rails 3 gave me problems :


HourEntry.before_save_callback_chain
NoMethodError: undefined method `before_save_callback_chain' for #

After some digging around ActiveRecord then ActiveModel and ActiveSupport I figured I could just access the _#{type}_callbacks method and then reject and select these arrays to get what was required. This is what I came up with to get the before_save callbacks that I was interested in.


HourEntry._save_callbacks.select { |callback| callback.kind.eql?(:before) }

This returns me the array of callback objects that are chained before I call save on the HourEntry model. If I want to check for a particular proc being in that chain then I can do :


HourEntry._save_callbacks.select { |callback| callback.kind.eql?(:after) }.collect(&:filter).include?(:archive_if_no_users)

It’s not optimal chaining a number of enumerable methods but I think it seems pretty readable.

I am hoping that the callback_chain methods return at some point (though I only used them sparingly) but more than that I’m hoping someone might be able to set me straight on how I’m going about getting around the callback chains on ActiveRecord and ActiveModel.

Twitter

Great web stats at @petrescue , the driving force behind the rebuild of their systems by @frontiergroup . http://t.co/MTvfoxnU

@frontiergroup about 3 weeks ago #

Search Posts

Featured Posts

Categories

Archives

View more archives