"Parent", "Children's" classes in ruby ​​(not inheritance)

Say I have two classes. One class, the “parent,” has many other “children.” This is not inheritance, I do not want parent methods to act on child objects. I want the child to be able to reference the parent, get the variables from it (child.parent.var) and call the parent methods that change the parent ( child.parent.update).

I need one object (which could be considered a child, but non-child, because this is non-inheritance) to pass a reference to another object when it is initialized. I would compare this with the parent relation of the children in the database, where we store information about the parent, so we do not need to duplicate it on each child.

Example:

class Parent
    attr_accessor :var

  def initialize(num)
    @var = num
  end

  def increase
    @var += 1
  end
end

class Child
    attr_accessor :var, :parent

    def initialize(parent, num)
        @parent = parent
        @var = num
    end

    def sum
        @parent.increase
        @parent.var + var
    end
end

parent1 = Parent.new(1)

child1 = Child.new(parent1, 2)
child2 = Child.new(parent1, 3)

child1.parent.increase # update the parent variable
child2.parent.var      # get the parent variable

The above code does work, but is there a better (more concise or more ruby ​​esq) way to achieve this?

Thanks so much for your help / thoughts.

+4
source share
1 answer

This is basically how it should be done :) There are several possible improvements, though, depending on what you really want to achieve.

Child ( parent accessor). , , . parent .

, :

class Child
  extend Forwardable

  def_delegator :@parent, :var, :parent_var
  def_delegator :@parent, :increase

  attr_accessor :var

  def initialize(parent, num)
    @parent = parent
    @var = num
  end

  def sum
    @parent.increase
    @parent.var + var
  end
end

Ruby Forwardable, . Child.

parent = Parent.new(1)

child = Child.new(parent, 2)

child.var
# => 2
child.parent_var
# => 1
child.increase
# => 2
parent.var
# => 2
# ^^^^ the increase method was called on the parent object

, , , .


parent :

class Parent
  # ...

  def child(num)
    Child.new(self, num)
  end
end

Factory Method, , . Child .

parent = Parent.new(1)
child = parent.child(2)
+3

Source: https://habr.com/ru/post/1660834/


All Articles