Skip to content

Django F() And Q() Objects For Rails

Recently I was browsing Django documentation deliberately looking for some ideas to cross-pollinate to Rails. F() and Q() objects looked like nice little hacks so I decided to implement them for Rails.

Continue reading ›
Tagged , ,

Rails Pro Tip: Invoke Command Line Commands From Rails Console

So there you have your command line prompt from Bash/Zsh/cmd.exe and there is so called Rails console which is basically IRB prompt with the Rails application loaded.

My tip suggests that you invoke some Rails commands, namely generator related commands and rake tasks, from the running Rails console. The reason to do so is clear and simple – it’s fast.

Continue reading ›
Tagged ,

Safe String Interpolation In Ruby

Age-Old Problem

Suppose you want to authenticate user from the login/password entered on the web from

    user = User.first(:conditions => "login = '#{ login }' AND password = '#{ password }'")
    
Such authentication code as we know can be easily fooled with the SQL injection. Thankfully in Rails there are parameterized queries and the above can be rewritten in at least 3 injection safe ways
    User.find_by_login_and_password(login, password)
    # or
    User.first(:conditions => ["login = ? AND password = ?", login, password])
    # or
    User.first(:conditions => ["login = :login AND password = :password", { :login => login, :password => password }])
    

Many Solutions (Haskell Included)

Parameterized queries cover most of the cases but what if you have large query with multiple parameters? You can quickly lose track of all the question marks and order in which parameters appear. Most likely you will prefer the latter, hash-based notation.

Continue reading ›
Tagged ,

Travel To The Core Rails 3 Methods Without Leaving IRB Prompt

In the previous post I introduced Reflexive gem which lets you browse the classes and modules for running application with Web UI. But we’re really often just goofing off at the IRB prompt, aren’t we? For this case I have extracted some portions of Reflexive to help with code navigation right from the interactive prompt.

Continue reading ›

Reflexive: Live Class And Source Code Browser

Background

Recently I was trying to understand how the Arel (Relational Algebra for Ruby) internals work.

The project has strong OO design and uses some metaprogramming techniques. Main code base consists of ~ 80 files, with files having 30 LOCs on average.

I’m totally cool with that kind of modular/small classes design, but for new comer (like me) it could be a little daunting and I had to draw some diagrams on paper before finally getting it instead of getting lost in inheritance chains, compositional patterns and so on.

Solved In SmallTalk 20 Years Ago

Squeak Class Browser

Indeed as with many other problems it’s been solved in SmallTalk for many years. Having live classes reside in live virtual machine is one the SmallTalk features that makes rich reflection facilities possible and which is missing from Ruby.

So Can We Have A VM Please?

While there is no Ruby VM in a strict sense what’s that Rails development server process we have running if not a VM with classes kept in sync with their «on the disk»/plain-text representation? Well at least it’s pretty close, also the fact that at least half of the metaprogramming stuff happens at load time definitely helps for better reflections (think klass.included hook, attr_reader, delegate methods)

What IDE?

Really I would love to have something like this built-in into my favorite IDE, but the problem is that I’m not even sure what’s mine favorite IDE is, and there is even less agreement on the subject in the community.

What Ruby Offers? Or Quick Recap Of Ruby Reflection Techniques

  • Kernel#method and Kernel#instance_method let’s you determine where the method defined on an object (instance of the object) comes from (an old trick taught by Dave Thomas). Less known is that with 1.9 you can get the file and line number of method definition with Method#source_location
  • Module#ancestors because of Ruby unified object model let’s you determine class ancestors, modules included in class, and modules included by another module. This also works seamlessly for singleton classes (i.e. when you have something like C.extend(M) module M becomes an ancestor of C.singleton_class)
  • Object#methods and Module#instance_methods when passed false as first parameter can be used to enumerate methods owned by class (as contrasted with returning owned and inherited methods by default)
  • Ripper Ruby parser although not directly reflection related Ripper is part of a standard library and is based on parse.y (the grammar file which Ruby interpreter uses) which automatically makes it always up-to-date with any Ruby syntax changes.

Get Reflexive

With the set of aforementioned tools in hand I went and created sort of proof-of-concept good old web-app with virtually no UI and enjoyed the process a great deal. It browses classes and modules, and the corresponding source code files with some interactivity twists (and a little dose of pink color).

Visit the GitHub project page to learn more about what it does and how to get it for your applications.
You can also check out the demo Rails 3 app with Reflexive installed running on Heroku but be warned that Heroku has old Ruby 1.9.1 which has some issues with the reflection capabilities Reflexive uses.

In Conclusion

It seems to me that live reflection is the really powerful way to get precise code navigation/autocompletion/refactoring tools in Ruby IDEs. It also should be possible to integrate Reflexive in RDoc or YARD to get more interactive source code listings, but I scratched my own itch now and have to move on :)

Exploring Latest ruby-lib Additions

Recently I was browsing through the NEWS file in the Ruby Subversion repository. Two methods added since the 1.9.1 release to the Enumerable module caught my attention. These two are Enumerable#chunk and Enumerable#slice_before. The docs for these are not available at http://ruby-doc.org/ so you’d need to go straight to the source code (by using the links above). The source code comments have a few usage examples but I wanted to expand on that, since I feel like they are if not crucial but certainly very useful additions to the set of excellent Enumerable/Array methods Ruby already provides. From this post you can learn how to:

Enumerable#chunk

Using this method you can chunk consecutive elements of the array into the sub-arrays based on some property calculated for the element by the passed block. The returned array has Array#assoc semantics, i.e. the first value of each sub-array is the property on which the chunk was selected and the second is the actual array of consecutive elements having this property. Suppose we’re implementing something like this Facebook feature: Here similar updates from the same user are collapsed so that you get less spam from your overly active friends. For the sake of demonstration we can assume that there are no special similarity rules and all updates from the same user are considered similar, assuming that you have Update model which stores the update related info (like who did what and on which date) you can chunk the similar updates together using the following code in controller:
class UpdatesController
  def index
    # since we're not interested in the property we're chunking the array on (user here),
    # we get just the chunks themselves with +map(&:second)+
    @chunked_updates = Update.order("created_at DESC").chunk(&:user).map(&:second)
  end
end
* Note this example requires Rails 3 and Ruby 1.9.2 to run properly And in the corresponding view:
<!-- views/updates/index.html.erb -->
<% @chunked_updates.each do |update_chunk| %>
  <%= render update_chunk.first %>
  <% if update_chunk.size > 1 %>
    Show <%= pluralize update_chunk.size - 1, "similar update" %>
    <!-- ... render additional updates here ... -->
  <% end %>
<% end %>

Enumerable#slice_before

This method is particularly when parsing files with the flat structure like:

Section 1 Header
Section 1 contents
...
Section 2 Header
Section 2 contents
...
Using slice_before you can extract such sections/slices. Turns out there are quite a few places where this could be useful: But probably the most useful of them is the following.

Structure aware log grep

Suppose you’ve got a production Rails app running with multiple clients/search engines making requests simultaneously. Now you need to investigate the issue with one particular client, or you want to monitor requests hitting some particular controller. Doing tail -f log/production.log outputs a lot of requests you’re not interested in. You can pipe the output to grep, but then you’d get one line per request, while the whole request log consists of multiple lines. One solution would be to use --context grep option which will show fixed amount of lines around the line where the match occurred, but the problem is that the amount of context lines is fixed while the amount of lines in request log may vary (for example if exception was thrown there will be the whole stacktrace, while for normal request there will be only about 3-4 lines). More robust solution would be to parse the log file into “slices” on the fly and show only ones you’re interested in. Here is the gist and some usage examples:

Show only local requests: 
tail -f log/production.log | grep_rails_log_file.rb 127.0.0.1

Show only GET requests: 
tail -f log/production.log | grep_rails_log_file.rb GET

Show only requests to /updates path: 
tail -f log/production.log | grep_rails_log_file.rb /updates

Use it right now

And the best part is that you can start using all the goodness right now even if your project is running on older Ruby version. The excellent Backports Library by Marc-AndrĂ© Lafortune already has these methods backported. Usually I don’t include the whole library but just rip out the needed method and place it under lib/core_ext folder. Tagged , ,

The YUI home page is frying my brains.
JavaScript library Links from the home page
The Yahoo! User Interface Library (YUI) 137
jQuery 45
Prototype 15
Damn, what’s so incredibly hard with doing less?

Ultimate YAML in IRb and all the think alikes

After I realized that I want to switch from default inspect output in IRB to YAML output, I googled and found this Secrets of the Rails Console Ninjas from Amy Hoy which suggested to use y method, then Geoffrey Grosenbach suggests class Object; def inspect; y self; end; end, but that would break for explicitly defined inspect’s, oh no! Evil-mokey-patch to the rescue:
IRB.CurrentContext.irb.instance_eval do
  def output_value
    printf @context.return_format, y(@context.last_value)
  end
end

Finally gave in and started to manage my dotfiles through github. Wasted me an hour or so to setup, but hey http://github.com/dolzenko/dotfiles/tree/master

too smart rubies

s = ""
s << 0 # just great
s << 255 # still cool
s << 256 # `<<': can't convert Fixnum into String (TypeError)
Now imagine that the null character comes from the variable and only under certain conditions. And the string then passed further to some component which just happily assumes the string ended at that null character. And I never liked that ASCII art method anyway. Probably wouldn't ever use it but many languages still suck at string concatenation.