views:

91

answers:

2

I'm new Ruby but been a .net dev for many a year. I want to implement composition within a couple of my model to make sure they are as loosely coupled as possible but have no idea where to start, or if this is really needed and I'm still thinking to much like a .net dev.

Can anyone give me some pointers on where to start.

Cheers Colin G

+2  A: 

Ruby is an object-oriented but dynamically typed language. Being a dynamic language, rubyists tend to use reflections and dynamic modifying of the code much more than .net developers. Of course because it's an object-oriented language you can use mostly the same principles as in .net, and you should too, but always look around and see how that same thing could be implemented in a more dynamic way.

For example the ActiveRecord ORM solves composition using a composed_of method that will dynamically add the appropriate fields and properties to your class. I'm not saying that this is the way it should be done (for example DataMapper, which is another ORM for ruby, choose a more "conservative" approach, and so resembles more like (Fluent)NHibernate), it's just an example of how things can be done differently.

Things like AOP, or DI aren't a foreign concept for dynamic languages, they are just usually done in an alternative way. Keep an open mind on the dynamic aspects of the language but don't overdo them.

SztupY
+1  A: 

Do you mean this sort of thing?

class Engine
    attr_reader :horsepower, :litres
end

class Gearbox
    attr_reader :manufacturer, :model_no
end

class Car
    def initialize(engine, gearbox)
        raise "Invalid Engine Object" if !engine.kind_of(Engine)
        raise "Invalid Gearbox Object" if !gearbox.kind_of(Gearbox)
        @engine = engine
        @gearbox = gearbox
    end
end


car = Car.new(Engine.new, Gearbox.new) 
stephenr