I’m reading a book called RailsAntiPatterns. In the converter method below, a new OrderConverter object is instantiated, and I assume self refers to an instance of Order class.
# app/models/order.rb
class Order < ActiveRecord::Base
def converter
OrderConverter.new(self)
end
end
# app/models/order_converter.rb
class OrderConverter
attr_reader :order
def initialize(order)
@order = order
end
def to_xml # ...
end
def to_json # ...
end
def to_csv # ...
end
def to_pdf # ...
end
end
- Why instantiate a new class inside of converter?
- Why does
selfneed to be passed as an argument? - Can you summarize in lay terms what’s going on?
Of course, it’s up to the choice of the author, but it’s probably convenient. For instance:
That reads quite nicely, which is important in the eyes of a Rubyist. As the original designer of Ruby, Yukihiro Matsumoto (Matz) has said:
Readibility for humans is, therefore, important if you wish to produce elegant Ruby code.
Quite simply, OrderConverter requires an order to convert. Since the method
converteris defined for instances of the Order class, an instance that wishes to convert itself will passselfas the argument to OrderConverter#new.I hope the above has done that for you.