Author Archive

Using Raw SQL snippets to create Thinking-Sphinx Indexes

We have used Thinking-Sphinx in several projects to implement search engines. Thinking-Sphinx is a wrapper in Ruby to use ActiveRecord with Sphinx. But in the project I’m working right now I had to solve a different problem: the user should be able to search for formatted values, however without using the formatting characters, i.e, suppose a field containing 111.444.777-35, the user should be able to find it searching for 11144477735 (or a substring of it).

The default behaviour for Thinking-Sphinx is to index the exact values for each column it scans, but we can by-pass it. The Thinking-Sphinx index definition allows us to use raw SQL to define which values should be indexed for each attribute. In my case, I used the native PostgreSQL regular expressions functions to get rid of the punctuation characters, indexing only the “clean” version of each value. My database column is called “entity_number”:

define_index

Continue reading

Code blocks with optional arguments in Ruby 1.8.x

Ruby 1.9 has some cool new features. One of them is the ability to define default values for the arguments passed to code blocks, like in the following example:

pow = proc { |a, b = 2| a**b }
 
pow.call 3, 3
# 27
 
pow.call 3
# 9

This is very useful, for instance, when we dynamically create new methods using metaprogramming and want some of the arguments for these methods to be optional.

class MyMath
  class < < self
    define_method :pow do |base, exponent = 2|
      base**exponent
    end
  end
end
 
MyMath.pow 3 # 9
MyMath.pow 2, 3 # 8

But in Ruby 1.8.x we can’t do that, we can’t define default values the arguments of a code block. So what if your application runs on 1.8.x and you need to dynamically create methods with optional arguments? There is a solution, not so elegant as the

Continue reading