Friday, February 26, 2010

Rails Source Code Walkthrough #1: the ActiveModel Module

I was taking a look into the fresh ActiveModel module of Rails 3 as of github revision #100644. Here is what I learned:

  1. Learned about new feature called autoload. Rails Inside has a small yet useful autoload example here. It is a mechanism to lazy load your modules, so delaying the load unless the module methods are actually called. A call to autoload simply marks it as a potential include, but the actual include takes place only when you first use something on that module. I has a syntax like the following: autoload :Callbacks
  2. Using autoload, the ActiveModel module loads a number of other modules such as: AttributeMethods, Callbacks, Dirty, Observer, Observing etc.
  3. Also, it initializes the I18n Internationalization with the default en locale.
What's inside AttributeMethods?
This module defines class methods that lets you define attribute methods for the objects. I learned that you can have prefix, suffix and affix appended to your attributes that go to to a default method. For example, consider the following example right from the code:

# class Person
      # include ActiveModel::AttributeMethods
      # attr_accessor :name
      # attribute_method_suffix '_short?'
      # define_attribute_methods [:name]
      # private
      # def attribute_short?(attr)
      # send(attr).length < 5
      # end
      # end
      # person =
      # = "Bob"
      # # => "Bob"
      # person.name_short? # => true
Isn't this amazing?
What's inside callbacks?
Callbacks module is responsible for firing your before, after and around callbacks on ActiveModel models.
What's inside Conversion?
Conversion module only has 3 methods, to_model, to_key and to_param . These methods can be overriden to allow custom conversion of the ActiveModel objects.
What's inside Dirty?
The dirty module is all about dirty tracking methods of your ActiveModels. It has methods like changes, changed?, changed, reset_attr! etc. that you can use to track changes of your model objects. Thinks like history tracking or audition on changes can be done using this module methods.
What's inside Errors module?
This module has everything that deals with generating errors on ActiveModel validations. One ruby feature I learned from this module that I didn't know before. Its something like an indexer in C#. Here is an example from the source code:

# When passed a symbol or a name of a method, returns an array of errors for the method.
    # p.errors[:name] #=> ["can not be nil"]
    # p.errors['name'] #=> ["can not be nil"]
    def [](attribute)
      if errors = get(attribute.to_sym)
        set(attribute.to_sym, [])
    # Adds to the supplied attribute the supplied error message.
    # p.errors[:name] = "must be set"
    # p.errors[:name] #=> ['must be set']
    def []=(attribute, error)
      self[attribute.to_sym] << error
What's inside the Naming module?
Naming module is all about singular, plural, human and such names for your models! This methods are used to define the routes as well as in views. You can override such methods to provide a custom pluralized name for your model.
What's inside observing?
Rails Observers provide you a clean implementation of the Observer design pattern. It extends on top of the default observer module from Ruby. These observers are often use for implementing Aspect oriented programming as well as the code that are neither part of models or controllers, rather fall in between the two. Email notification is an useful example from Rails Guides.
What's inside the Railtie module?
Well, not much! But it glues up ActiveModel with Rails! Just two lines of code as folllows:

require "active_model"
require "rails"
What's up with Serialization?
It has only one method that generates a hash based on the serializable attributes with :only and :except filter!
What's inside Serializers?
It has two serializers, one for json and another for xml. This two works great out of the box. However, if you need to tweak it, it should be very simply done by subclassing this classes.
What's inside translation?
It translates your model attribute names to match your locale using I18n. The default skim looks for the following naming in your local yml file when called through the method human_attribute_name
Whats inside Validations?
This is a freshly renovated module for Rails 3, as it merged the validates_presence like methods into a single method validate that lets you keep all your validations for a model with a single call. Also you can easily reuse custom validators through out your models.
But this forked a few more modules, one per kind of validation. All these validations and your potential custom validators will probably be descendent of the Validator class that has the following method:

# Override this method in subclasses with validation logic, adding errors
    # to the records +errors+ array where necessary.
    def validate(record)
      raise NotImplementedError
Some in-built implementation of this validator are acceptance, confirmation, exclusion etc. I learned something new here, the NotImplementedError exception.
So, what's the big learning here?
  1. I will use Modules to modularize my ruby code. This perfectly makes sense and also this is how one can come up with plugins out of their code base. Having the small bits in a module also facilitates reusability inside a project.
  2. The source of ActiveModel is very simple and completely ignorant of its underlying database. This is the big change of liberating Rails from ActiveRecord, which I think is not a matter for most rails developer anyway! But its a good lesson learned.
  3. Once I see some time, I would like to jump in to the development of Rails, at least make some initial contribution.
Stay tuned for more posts on Rails 3 source code.

Thursday, February 25, 2010

Why would you spend $10 to learn to use Basecamp?

This is sounding very strange to me indeed! 37Signals is very much known for creating the simplest of interfaces and I really found people finding it very intuitive. But this is strange... now they are asking people to buy a book for $10 to learn how to use Basecamp! Can you believe it? See the sales post (!) here at "Sams Teach Yourself Basecamp in 10 Minutes" is a comprehensive guide to Basecamp

Tuesday, February 23, 2010

Ruby on Rails Interview Questions: Advanced

In my previous post, I listed a few general interview questions for Ruby on Rails jobs. This one is intended to be more of an advanced level, not for the rookies :-)

  1. What is Rack?
  2. Sketch out a deployment architecture of a Ruby on Rails application utilizing multiple servers.
  3. How can you secure a rails application to counter for Session Fixation?
  4. Where can I get the core rails framework source code?
  5. How can you reuse the models from one rails project into another?
  6. Explain one plugin that you extracted out of your source code.
  7. What is the difference between pre-initializers and initializers?
  8. How can you easily switch your logger to use Log4r?
  9. How would you design the logging standard for your rails application?
  10. How can you implement asynchronous messaging in Rails?
  11. What will you do to look for a possible memory leak in Rails application?
  12. How can you run a profiler?
  13. What is lambda?
  14. What is Proc? When did you use this?
  15. How can you use before and after callbacks of your rails methods to halt a database insert/update/delete?
  16. How can you reuse your before and after callback methods across multiple models?
  17. Define an architecture to store files uploaded to an application so that they are only accessible to valid users.
  18. How would you change your asset storage to use a static server?
  19. Explain one situation when you used rails caching.
  20. What kinds of caching comes in-built with Rails?
  21. Can you explain the use of 'dynamic' features of Ruby on the core Rails framework?
  22. How can you call a SOAP web service from a rails application?
  23. Your application needs to send a lot of email notifications. How would you design the notification so that the end user doesn't get stuck for email sending delays?
  24. What is a mongrel cluster?
  25. Can you explain if the clusters share a same memory? Can one cluster handle a request from a client that was handled by another?
  26. How would you internationalize your application interface?
  27. How can you create a rails generator?
  28. Have you ever used a polymorphic association?
  29. How can you define a plugin that adds a new class method to ActiveRecord::Base?
  30. What are the three most significant changes in Rails 3 in your eyes?
  31. How can you implement complex reporting using ruby on rails?
I am sure this list will go on and on. But I have found most people asking questions about scalability, deployment issues, security and such architectural level questions to extract out the in-depth understanding of such core concepts. Where to learn more on such advanced stuffs? Ruby on Rails Guides and Stack Overflow are my favorite places. However, its good to keep an eye on the edge rails to see what's happening today! 

Monday, February 22, 2010

Ruby on Rails Interview Questions

Ruby Specific Questions
The best place for learning ruby is to get started with the programming-ruby. It fairly covers the important bits in a very readable language. Here are a few quick questions on ruby:
  1. What is rubygems?
  2. What is a Symbol?
  3. What is the difference between a Symbol and String?
  4. What is the purpose of yield?
  5. How do you define class variables?
  6. How do you define instance variables?
  7. How do you define global variables?
  8. How can you dynamically define a method body?
  9. What is a Range?
  10. How can you implement method overloading?
  11. What is the difference between '&&' and 'and' operators?
  12. What is the convention for using '!' at the end of a method name?
  13. What is a module?
  14. What is mixin?
  15. How will you implement a singleton pattern?
  16. How will you implement a observer pattern?
  17. How can you define a constant?
  18. How can you define a custom Exception?
  19. How can you fire a method when a module is included inside a class?
  20. What is the default access modifier (public/protected/private) for a method?
  21. How can you call the base class method from inside of its overriden method?

Rails Specific Questions
A thorough reading of the articles at Ruby on Rails Guides can be very useful for starters as well as a refresher for veterans. The following bunch of questions are specific to rails, in no particular order. The Pragmatic Bookshelf has a fantastic book for beginners called Agile Web Development Using Ruby on Rails.
  1. Define the Rails MVC implementation using an example.
  2. What is a named scope? (or Scope in Rails 3).
  3. Can you give an example of a class that should be inside the lib folder?
  4. Where should you put code that is supposed to run when your application launches?
  5. What deployment tool do you use?
  6. How can you migrate your database schema one level down?
  7. What is an observer?
  8. What is a sweeper?
  9. How can you implement caching in Rails?
  10. What is a filter? When it is called?
  11. How can you divide your controllers into separate modules?
  12. What is RESTful routing?
  13. How can you list all routes for an application?
  14. How can you send a multi-part email?
  15. Is it possible to embed partial views inside layouts? How?
  16. What is the purpose of RJS?
  17. How can you create a REST API for your application?
  18. How can you define a new environment called 'staging'?
  19. What is Rake?
  20. What is Capistrano?
  21. What is a polymorophic association?
  22. How can you implement a polymorphic association?
  23. What is a has and belongs to many association?
  24. What is the difference between has_one and belongs_to?
  25. How can you implement single table inheritance?
  26. What is eager loading?
  27. How can you eager load associated objects?
  28. How can you add a custom validation on your model?
  29. How can you implement a custom theme for your forms?
  30. Why is fields_for used for?
  31. What is the purpose of a helper method?
  32. What is flash?
  33. How can you install the missing gems that are required by your application in the simplest way?
  34. How can you implement internationalization?
  35. How can you show search user friendly urls instead of using only numeric ids?
  36. How can you configure your application for different environments?
  37. How can you instruct rails logger to ignore passwords and such fields while logging?

Test Frameworks
Ruby on Rails has a number of built-in and a few other third-party test frameworks. Here are a few sample questions on such frameworks:
  1. Are you familiar with unit testing?
  2. How does functional testing differ from unit testing?
  3. Have you ever used a mocking framework?
  4. Are you familiar with BDD using RSpec or Cucumber?
  5. What is an alternative to using test fixtures?
  6. How can you reuse part of a text fixture?
  7. How do you specify associations in the test fixture yml files?

Plugins are the principal mechanism to reuse code. The open-source community is at full-bloom when it comes about plugins. The Rails Plugins site has a really good list of such plugins from the community.
  1. What plugin would you recommend for user authentication and authorization?
  2. What plugin do you use for full-text search?
  3. How can you implement a state machine?
  4. What is the difference between a plugin and a gem?
  5. How can you create a plugin?
  6. Can you please name a few useful plugins?
  7. How can you implement a search feature that searches for multiple models?
  8. How can you upload a flie to a server?

Architecture Related Questions
This questions can be from different angles like: quality, security, scalability, manageability, interoperability, reusability and all the other ilities you name! Here are a few example questions:
  1. Is Rails scalable?
  2. What are the key deployment challenges?
  3. How can you safeguard a rails application from SQL injection attack?
  4. How can you secure a rails application?
  5. How can rails engage with a SOA platform?

Community Related Questions
I see a fairly large community on Github, Stack Overflow, RailsCasts, The Riding Rails Blog and many more. Some interviewers may want to see if you are connected to the community. The following questions may help you prepare :-)
  1. Can you tell me a few good community resources for Rails?
  2. Where would you reach out to get the community to answer your questions?
  3. What's new in Rails 3.0?
  4. Which famous applications are built using ruby on rails?
I plan to polish this document on a later revision. But in the meanwhile, if you feel like contributing, you can start commenting with the answers, more questions or suggestions. I believe this will not only help people getting ready for their next Rails job, but also for everyone to see what knowledge we are missing...
Disclaimer: This is not a shortcut, rather its kind of a check list that may help you with an interview.