Tags: ruby

Template with Context using ERB

Recently, I was required to build a template rendering component that should render within a dynamic context, i.e. it would have methods / variables defined within a predefined context available during rendering, apart from what was provided directly.

For simplicity we chose ERB, since we can place them within locale files for internationalisation and designers could edit them with ease if need arises.

Following is a very simple implementation. Since we extend OpenStruct we can simply pass a hash to it during instantiation and all the keys will be accessible as methods and will be exposed directly during rendering.

The benefit of creating a separate abstraction is that it creates a sandbox environment for the template processing. This allows us to have more control over what gets exposed during processing and prevents accidental leakages into the context.

The main method here is the render method, where we utilise the ERB library. We create an ERB instance with the supplied template string and then call result, to which we supply the current execution context using the current binding.

The nifty trick here is the method_missing definition. Here we override the default definition which OpenStruct uses behind the scenes to access the keys as methods on the seed hash. We check for the existence of the method and delegate it to self (hash) when available, otherwise we delegate that method over to the special object available at :_object key, which serves as our ‘dynamic context’.

The usage would look something like this :

This gives us the flexibility of rendering the given template in any context and hence the templates could be designed flexibly. Since we built this as a rubygem, it allows us to expose template processing in a way that allows the host application to build it’s own context with custom functions / attributes to be used during rendering.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

Google Code Jam 2014 Qualifiers

Google Code Jam has always been a competition I have cherished, simply because the problems they post are brilliant and the closest to reality as compared to problems of other competitions. They’re always fun to read, disect & solve, more often than not, the solutions are reasonably trivial (especially for the qualifiers) yet extremely subtle & deceptive.

Today I want to share the solutions of 3 problems I was able to solve, the code should pretty much speak for itself because none of it is very complex.

  1. Magic Trick

    This one was the easiest of all, more of a warmup I suppose. Here’s the solution :

  2. Cookie Clicker Alpha

    Based on Cookie Clicker game developed by Orteil, this one was slightly trickier, and required a little bit of math. I solved it with a recursive algorithm first, then optimized it into an iterative one to pass for the large input. Here’s my solution with both recursive and iterative parts :

  3. Deceitful War

    This one was really subtle, easy enough to understand but hard to implement. It took me a while to put my understanding of how much being deceitful at the game called War translated to my points. Here too I solved both the normal game War and Deceitful War recursively first (it’s just easier to think recursively thanks to Lisp), then translated those to their iterative counterparts. Here is my solution with both recursive & iterative parts :

  4. VN:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VN:F [1.9.22_1171]
    Rating: 0 (from 0 votes)

VIM – Toggle Ruby Hash Syntax

Ruby 1.9 introduced a new json style ruby hash syntax. Although we can use this to define static hash objects and puts a limitation on the key we can use, it’s a fairly neat syntax nevertheless. However I work on several projects, both new and old and hence the new syntax is not always readily available.

To demonstrate the sheer power of regular expressions & VIM, here’s a tiny snippet that allows you to quickly toggle a ruby hash syntax from one form to other.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

ActiveRecord like where for array of hashes in ruby

Edit : Updated the code as per the suggestions made by Masklinn.

Recently I was working on Issue#1 of my Soulmate Rails gem, which is a very simple and obvious optimization that I should have thought of myself. Thanks to lephyrius though for pointing it out. In my search method I was looping through the search results and calling find on each to get it from db. The fix involved to instead use a single where for all ids so that it translates to a single db call. A simple fix as well as an optimization.

However once I implemented it, I notice my tests were failing. On closer inspection i found they are failing because the models I created for testing using supermodel gem, didn’t have a where method. For a moment I thought WTF, and then I headed on to supermodel and looked through the source and to my surprise, it in fact did not implement a where method. So I took it upon myself to do it.

Here’s the generic code I wrote that could be applied to any array of hashes :

Now you can do

And you will get what you’d expect.

I updated supermodel in my fork to support such a where method and have sent the original author a pull request, hopefully it will get pulled soon.

All my tests pass now! Yay! I have released v0.3.0 of Soulmate Rails. Be sure to check it out.

PS : How about a code review ? Is this optimal or can it be improved further ? I’d like to hear thoughts from others.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Soulmate Rails

One of the most common things to do in any standard rails web applications is auto-completion. One interesting solution to this is by using redis’ (which is blazing fast) sorted sets, storing key value pairs for partial matches. For example, if we wish to index the word ‘Dhruva Sagar’ (my name), you can simply create key -> value pairs of ‘d’ -> ‘Dhruva Sagar’, ‘dh’ -> ‘Dhruva Sagar’, ‘dhr’ -> ‘Dhruva Sagar’ and so on. Since hash lookups are of constant time complexity O(1), they’re very fast and hence the completions are too! Combine this with using sorted sets of redis to easily order / sort information on a specific criteria and you have a blazing fast solution. Of course the actual implementation can be further optimized by means of caching query results and make the system perform even further.

Soulmate is a cool gem by the guys at SeatGeek that provides a pretty cool implementation of the same. However it’s implementation wasn’t quite a good fit for my case since I wanted to work with a rails application and didn’t want to either host a separate server or mount the provided sinatra app inside of rails. I came across this nice post by Pat Shaughnessy – Finding your soulmate: autocomplete with Redis in Rails 3.1 which showcases how one can use the Soulmate gem and use it’s API to roll out your own auto-completion engine within your rails 3.1 application very easily.

This inspired me to fork Soulmate and extend it to build a Soulmate Rails gem over the weekend which provides a clean and intuitive API to do this from within Rails. Please do check it out, star it, fork it and use it to your hearts content :) . I’ve released it in alpha phase right now but it is fully usable with a reasonable test coverage. I’ll be contributing a lot to this, hopefully you find it useful too.

UPDATE : I released the first stable version 0.2.1, it should be usable as is without any issues.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

VIM in my muscle memory

I have been an ardent VIM user for almost 4 years now, and it’s been a while since I have been wanting to write this Blog. My motivation is not to showoff or to start any flame war against any other popular text editors that may or may not be better ;), but to simply showcase the things I like and have come to appreciate in VIM, and show why you should seriously consider it when deciding which programming editor you should use. Hopefully I will be able to do justice to VIM – the Ultimate Programmer’s Editor.

The beauty about using VIM is that it converts the task of text editing / manipulation into a programmable activity. It provides you with a framework to work with your text in a way which allows you to think of it in terms of simple patterns, patterns which you can repeat, store (macros), copy & even combine together. This also makes the process of learning VIM interesting & fun! Add to that the fact that you can easily extend your VIM with a wide variety of plugins & themes contributed and shared openly by a vibrant community is just icing on the cake!

Initially when you start out with VIM it feels quite alien and ancient to say the least, also because the default configurations in VIM aren’t that optimal, so it might take a few days to get a hang of things, but once you do, it will motivate you to do things faster. The more you do, the more you obsess on doing things faster and with fewer and fewer keystrokes as possible (you might want to have a look at http://vimgolf.com for a bit of fun in that respect :)), the more you discover what VIM has to offer.

Over a prolonged period of usage, slowly and steadily VIM commands creep into your muscle memory and the vastness of the abilities and features of VIM which overwhelm you in the beginning, come to you as second nature. This is my attempt to describe various elements of VIM that are now in my muscle memory and use them on a daily basis.
Read More →

VN:F [1.9.22_1171]
Rating: 4.8/5 (16 votes cast)
VN:F [1.9.22_1171]
Rating: +10 (from 10 votes)

Getting started with Ruby – TOC

Hi,

I have written a series of articles (in several parts) in an attempt to guide beginners to get comfortable with Ruby. This article is my attempt to build a TOC (Table of Contents) for it to act as an index for people to get a brief idea regarding what each article is about and help them get to the sections they are interested in.

  • Getting started with Ruby – Part 1 : In this article I begin with an introduction to myself and my motivation behind writing these articles. I give an introduction to Ruby, about how to get started with building your development environment and introduce a few tools that ship along with Ruby which will make your life that much better.
  • Getting started with Ruby – Part 2 : In this article I introduce Ruby in slightly more detail and I get started with describing different data types in Ruby. I cover Strings and Numbers in this article.
  • Getting started with Ruby – Part 3 : In this article I continue from my previous article describing data types in Ruby and cover Ranges and Arrays.
  • Getting started with Ruby – Part 4 : In this article I continue further and cover Hashes, one of the most commonly used data types in Ruby. I also introduce blocks and about using blocks with functions.
  • Getting started with Ruby – Part 5 : In this article I move onto describing various looping constructs in Ruby, and also various flow control modifiers in Ruby. After that I introduce Variables, Symbols, Constants, Methods and Global Variables in Ruby.
  • Getting started with Ruby – Part 6 : After having covered basics of various constructs in Ruby, I considered it better to take a problem statement and solve it in Ruby to bring most of what we’ve discussed into use. I chose Google Codejam 2009′s qualification round problem – Alien Language

I tried to be clear, precise and specific. My intention was write more code than to waste time in trying to explain and so I’ve used code comments to help people understand what each part of the code is meant to do. I have plans on going further and go onto describing classes & modules, sometime soon, even though I expected more people to read and give their feedback, but owing to a lot of work and hence a lack of time, I haven’t been able to do much justice to the same, but hopefully I will be able to do so very soon. I hope it helps people appreciate Ruby and motivate them to learn and understand it.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

MongoMapper Plugin – Versionable

There was a requirement at one of our projects here at Artha42 Innovations Private Limited that our Mongo Mapper documents have inherent versioning so as to be able to track the changes being made and also if required revert the changes to a previous state. Since we’re using MongoMapper, I set out to create a simple plugin for the same to add the required functionality.

Initially, from the initial research I did, I found Shapado had an implementation of exactly what I wanted, however when I studied and understood their implementation in detail, I realized that it doesn’t really work that well in most scenarios, especially the ones we were tackling in our project. Shapado’s versionable allows you to define a set of keys for a document, whose changes would trigger creation of new versions. However in our project we needed to track changes at the complete document level, i.e. even for changes in the associations. Also the versions were embedded within the document itself, which implied that the document would grow in size very rapidly, even though our changes in each iteration could be minor, since each version would literally be a snapshot of the complete document itself.

So we made quite a few design changes in the same, externalized the versions, changed the way one would enable versioning since in our case we wouldn’t be keeping track of changes only in specific keys. Even here, we found that there were certain bottlenecks in the case if there were a whole lot of versions, for which we introduced the :limit feature which allows us to define how many of versions would need to be loaded instead of loading all of them at once.

The result of it was mm-versionable.

If you have any comments, suggestions, requests, queries or feedback, please do let us know in the comments section below.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Calculating Hashes

Showcasing how to calculate hashes in Java, C# and Ruby!
Read More →

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Getting started with Ruby – Part 6

After having covered most of the basics of Ruby, lets get started on an actual problem, just like I had promised in my previous article – Getting started with Ruby – Part 5

I am taking a relatively simple problem that came in Google Codejam 2009 qualification round. Here is the direct link to the problem – Alient Language
Read More →

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)