Ruby Eval To Remove Duplications November 19th, 2006

I have been using rails extensively for about one and half months. Rails is based on ruby. So I spend time to learn ruby. I design the database with mistake. I have 8 tables that share similar attributes. Instead to make 1 table associates with 8 tables or 1 big table only (inheritance model), I made 8 different tables. The effect of this decision is I have many similar methods in my controller. For example this is one of the duplications:

class ThermoDetectorController < ApplicationController
  ....
  def new
    @thermo_detector = ThermoDetectorOrderLetter.new
    @goal = 'create'
  end
  ....
end
class QuartzHeaterController < ApplicationController
  ....
  def new
    @quartz_heater = QuartzHeaterOrderLetter.new
    @goal = 'create'
  end
  ....
end
Ruby eval to the rescue. I have to explain what is eval. It is a method from Kernel module. I evaluates the ruby expression(s) in string.
class ApplicationController < ActionController::Base
  def first_preparation(class_param)
    @class_controller = class_param
    @controller_varname = Inflector.underscore(@class_controller.to_s.gsub(/OrderLetter/, ''))
  end
  ....
  def new
    eval "@" + @controller_varname + " = @class_controller.new" 
    @goal = 'create'
  end
  ....
end
And in our controllers:
class ThermoDetectorController < ApplicationController
  ....
  def initialize
    first_preparation(ThermoDetectorOrderLetter)
  end
  ....
end
class QuartzHeaterController < ApplicationController
  ....
  def initialize
    first_preparation(QuartzHeaterOrderLetter)
  end
  ....
end

You can see I can remove new method from both controllers. I told you before I have 8 tables; that means I have 8 controllers. The new method is not the only duplication. So ruby eval is my hero. With ruby eval, I can remove duplications from models too.

Sorry, comments are closed for this article.