Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax Checking or "Compiling" a Ruby on Rails Application

I'm new to Ruby and recently ran into an issue comparing to values when creating a Ruby on Rails application. In a controller I had the following statement that always returned false:

if (user.id != params[:id])

The problem was the user.id (which is an Active Record) is an integer and params[:id] is a string. It took me a while to figure this out and I finally changed it to:

if (user.id != params[:id].to_i)

Now the statement works as expected.

To avoid this error in the future is there a way to "compile" or get Ruby to warn you if you try to compare 2 different types? Some other issues I've ran into that I would like to "compile check" are:

  • Warn me if I create a variable but don't use it. To help check for typos in variable names.
  • Make sure a method exists in a Class so I can avoid method name typos and also to help refactoring, for example if I rename a method.

I'm currently using Ruby 1.8.6-27 RC2 with Rails 2.3.2 and RadRails IDE on Windows.

like image 746
Chris C Avatar asked Jul 09 '09 14:07

Chris C


2 Answers

Ruby doesn't allow you to redefine the == operator for Object. In ruby 1.8 you can't, Ruby 1.9 was supposed to do but I haven't been able to get my script working for core classes. It works well for custom defined objects.

class Object

  alias :equal_without_warning :==

  def ==(object)
    unless self.class == object.class
      warn("Comparing `#{self.class}' with `#{object.class}'")
    end
    equal_without_warning(object)
  end

end

Assuming I didn't do some stupid coding error, the answer is NO: you can't check whether you are comparing different type of objects.

Also, I would say you don't. Actually Ruby isn't designed to work in this way, this is more a java approach rather than Ruby style.

like image 43
Simone Carletti Avatar answered Sep 22 '22 14:09

Simone Carletti


Test first, then code. If you write tests that cover all branches of your application, you get the assurance that your code both runs and produces correct results.

EDIT: I should point out that the ability to compare two types, not depend on method names until the last second, etc. are core features of Ruby.

You don't call a method so much as you send a message to an object. The object is then responsible for figuring out how to handle the method. In Rails this is used to access DB columns in ActiveRecord. There are no methods for the columns until a message with the column name is sent to the object.

Static typing in Ruby goes against the duck typing system. One can often get polymorphism for free without worrying about complex inheritance/interface schemes.

I suggest embracing these features and compensate for the uncertainty through testing

like image 114
Ben Hughes Avatar answered Sep 21 '22 14:09

Ben Hughes