Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Composition in ruby

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

like image 678
pythonandchips Avatar asked Dec 28 '22 15:12

pythonandchips


1 Answers

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) 
like image 124
stephenr Avatar answered Jan 15 '23 15:01

stephenr