Sohan's Blog

Things I'm Learning

Summer of 2010! Europe, Here We Come!

I just completed my Winter 2010 semester at school. It was so far a good one. I pushed my papers and presentations on the courses of this semester at http://smsohan.com/#courses If you are interested to read my paper about Tabletop Application Testing or Communication Challenges with Distributed Agile Teams, you are most welcome at my site.

However, its time to look ahead to the summer. And I hope this will be a good one! I just received my driving license after a wonderful training from Drashko and Gordana at the Green Light Driving School. If you are looking for a caring and professional driving school in Calgary, I highly recommend them. They will make it easy for you.

Well, driving license comes with an obligation to buy a car :-) I am right now looking for one used car, probably from Toyota, Honda or Nissan, as people told me these are more reliable than others. I am not sure if I will be buying a car soon, but I already got visa for a Europe trip, my first ever. Its gonna be our second honeymoon in the European land :-) We will be going to Norway for attending the XP 2010 conference where I will be presenting my research paper on Email Auto-Tagging with User Stories. However, we are planning to see a part of Amsterdam and Stockholm alongside Norway. I have heard all the good things about these sites during summer… staying tuned to that!

I will also be working on my research project as well as my job at Wairever Inc. This summer will be a busy one. But I am hoping the summer in Calgary will be a lot of fun with friends and at work…

One little realization: I figured out that there are two crowds in the software world. One crowd has lot of respect for open source stuffs like Ruby on Rails and another crowd has that for “established” big players like .Net or Java. With this realization, I am focusing on getting my .Net knowledge in sync with recent developments as of .Net 4.0 and VS 2010. I am always reading the blogs and MSDN… but this time I will look into one/few books that give(s) a complete and detailed picture about the deltas in .Net 4.0.  However, I will keep posting on my Drink Rails blog as usual, almost daily.

Do you have any recommended book for .Net 4.0? Please use the comments area for that.

Comments

Sohan
Thanks Ashic for stopping by and commenting… Yes, you are right, there are the four categories.
ashic
Congrats on err…everything ;)
I'd argue there are a few more types than just those two. There are .NET junkies who respect rails. There's a reason ASP.NET MVC is so great…some of those junkies saw that webforms is shit, that Rails does web far far better and chose to bring something similar to the .NET world. The same guys are promoting patterns and practices that came about partly (if not largely) from the Rails world. I'm a .NET guy, so I know that that's true. I'm sure there's a fourth category that goes the other way (i.e. they're OSS people who respect .NET etc.).

Using Authlogic and Single Access Token for API Access

Bynarylogic’s authlogic has gained much popularity for its out of the box solution to ruby on rails authentication. Yesterday, I was working on giving API access to my ruby on rails application so that other apps can use my RESTful services. The authenticated API access usually involves the following steps:
  1. API_KEY or a token to identify/authenticate an API call.
  2. Authentication of an API caller using the API_KEY.
Authlogic comes with in-built support for this. The following steps will do it for you:

Comments

jlfenaux
Thanks the clear explanation about single_access_token, I was looking for.

flash.now - Did You Know?

Well, I didn’t know this until late. If you are like me, you have often wondered when you saw those unwanted flash messages appearing after a request, sometimes after ajax requests when you do a redirect, all on a sudden that flash shows up!
Well, as you have thought, the Ruby on Rails people have solved this problem way before now. The solution is to wisely use flash.now[] and flash[]. Here are a few tips:

Use flash.now[] when you are flashing:

  • on ajax requests
  • before a call to render :action => :my_action, as often found in failure cases of create and update actions
Use flash[] when you are flashing:

  • before a redirect_to, often found in the success cases of create and update actions
In general, use flash.now[] when you don’t want to carry over the flash to the next http request and flash[] otherwise. The FlashHash class has more detail on this at the ruby on rails API page. Hope this helps you to get rid of those annoying and often embarrassing out-of-context flash messages!

Comments

Sohan
Thanks Severin for your comment and pointing the typo.
Severin
Helpful explanation, thanks!

But there's a little typo: "Use flash.NEW[]…" should be "Use flash.NOW[]…"
Sohan
Hi Arif, you are welcome. Happy to help :-)
Arif
Nice tips. i think we can utilize it in our project to get rid of some mysterious flash messages :) Thank you.
Sohan
You are welcome Ashif.
Ashif Manjur
Thanks for this nice little useful post…

What’s Up Next?

Hello Readers:
Wish you all are doing great as the Spring already started :-)
Recently my grad courses are keeping me busy with assignments and projects as the term comes close to an end. So, I haven’t had much time to spend on blogging other than posting the Ruby on Rails link blog called www.DrinkRails.com. However, for my readers, I thought I would post the recent presentation that I put for the Agile course here:

But I am looking forward to start a new project with Wairever (www.Wairever.com), a Calgary based health care IT solution vendor. I hope that will fuel me with a lot of new concepts and as always, I will try to keep my learning posted here at my blog. Stay tuned! BTW, if you are Ruby on Rails developer or wanna be so, please let me know your feedback about the DrinkRails.com link blog.

Ruby on Rails Security Review: An Experience Report

Image credits to Wink on Flickr (creative commons)

I was reviewing a Ruby on Rails source code to see the security implementations they have so far. They are about to launch their product for the first release and wanted to ensure they have the most obvious things checked. So, in a sense it was not supposed to be a hacking job for me, rather to check if the most well known security measures are in place. This is what I looked into so far:

  1. Password: Password was encrypted using a salt. However, the default logger would log the password as they didn’t use the filter_paramerer_logging method.
  2. Cross-Site Scripting: I was able to easily inject a script by just entering <script>alert(‘Script’)</script> when I signed up to the system and every time it would open an alert window whenever I navigated to a new page! So, I recommended them to use <%= h %>. However, Rails 3 does a good job of making this a default.
  3. Authorization: I found the weakest measure in the implementation of Authorization. For an example, there is a calendar in the web app where one can add/remove events. I found that any logged in user, not necessarily the event owner, could change/remove any calendar event. This was a shocker. Next, I found this same thing happening to the core models as well. The catch here is, they had a filter that checked if a user was logged in, but they didn’t check if a user has rights to modify an instance of the object. For example, there is a project model, that can only be modified by the project owner. However, this per object ownership was not authorized and it was a huge potential security bug in my opinion.
  4. File uploads: The app was designed to upload the files to a folder underneath the public folder. Which means, if the rails server was down, apache would serve the files directly to the user bypassing whatever security measure was taken inside the app.
  5. PRG violation: This is a good idea to follow a post-redirect-get pattern when an object is modified through post/delete/put to ensure pressing the browser refresh button doesn’t re-invoke the change. This wasn’t done at some places which might end in multiple payments and such severe risks.
  6. Direct public release: I was a bit concerned that they wanted to go public release with their first ever release, even before having an alpha or at least in-house user. This is important because this application deals with money and credit cards. Trust is very important for such apps. So, I advised them to try this for some real works at home other than the “asdf asdf asdf….”(!) kind inputs. This will help them spotting some of the odd behaviors early and cause less embarrassment.
It was only a 4 hour assignment for me. Also, I was only limited to the source code and the test deployment that they have now. However, it seemed to me that, they might spend a few hours to fix the obvious errors and do some in-house real use before going to a public release.

Ruby on Rails or Rails on Ruby?

All on a sudden, this thing popped up in my mind. What we are calling Ruby on Rails, is this actually “Ruby” on “Rails” or the other way around? Is this upside down? Here’s my mental picture of the RoR framework:
Image credits to Foo Fighter on Flickr(creative commons)

  1. Ruby is a self-sustained language. As a language this is completely ignorant of the Rails Framework. So, I think there is no dependency from Ruby to Rails.
  2. Rails is a framework built using Ruby as a language. So, there is a strict dependency from Rails to Ruby.
What do you think? Would you call it “Rails on Ruby” or “Ruby on Rails”? I see a point of agreement for the ones who want to call it RoR, no damage done :-)

Lets see how this “on” preposition works for other language/platform pairs:
  • Java on Struts vs Struts on Java
  • PHP on Cake vs Cake on PHP
  • C# on .Net vs .Net on C#
Confused? Well, then you can use RoR for now!

Comments

Sohan
I like the way you put it :-) "Rails are those things that trains moves on", taking literal meaning in this way would mean something very different for "ruby"!
Anonymous
I think you've messed it up ;). Rails isn't a framework. Ruby on Rails is. So it is not Ruby (language) on Rails (framework). Rails are those things that trains moves on. So Ruby on Rails means (at least for me) something like "accelerated ruby with a lot of constrains". And this is a name of a framework. Rails on Ruby would be something like: "this poor guy Ruby takes those heavy rails on his shoulders and walks in pain with it"

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 = Person.new
      # person.name = "Bob"
      # person.name # => "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)
        errors
      else
        set(attribute.to_sym, [])
      end
    end
    # 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
    end
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
activemodel.attributes.underscore_model_name.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
    end
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.

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

Comments

Sohan
Hi Ashic, thanks for stopping by!
They claim to have 3 million users on Basecamp. I think $20K is not something that makes them any richer!
In fact I would think it gives a wrong signal, like you need to learn by reading a book to use Basecamp, what people seem to know anyways!
ashic
Times are bad bro….10 x 2000 = 20,000 ;)

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! 

Comments

Anonymous
Hi,



Thank You….
gopi
Hi,

Thank you verymuch….
bologna03
Hi

Tks very much for post:

I like it and hope that you continue posting.

Let me show other source that may be good for community.

Source: Phone interview questions

Best rgs
David
Abdul barek
AWESOME Questions. Please uncover all answers. Really can't wait any more…
Sohan
@Milan, you will see the answer if you google! But I will try to do a follow up post with the answers of these questions :-)
Milan Dobrota
Nice idea! Looking for answers. :D

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
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.

Comments

sandeep kumar
Thanks Nice Post….
sandeep kumar
Thanks Nice Post…

Best Regards,
Sandeepleo
rine
Hi

Tks very much for post:

I like it and hope that you continue posting.

Let me show other source that may be good for community.

Source: It interview questions

Best rgs
David