Defining nested classes both directly and through

Suppose I model my home storage system. I have a bunch of different types Container, and I found that many of them have decorations in them or on them, which I installed a little helper code for this general case.

Among my containers are mine Mantlepieceand mine Bookcase. I only store jewelry on the first; while the latter has all the decorations, as well as hardback and soft drive books.

Here's the initial attempt:

module Properties
  def has_ornament
    include OrnamentThings
  end

  module OrnamentThings
    module Things
      class Ornament
      end
    end
  end
end

class Container
  extend Properties
end

class Mantlepiece < Container
  has_ornament
end

class Bookcase < Container
  has_ornament

  module Things
    class Hardback
    end

    class Paperback
    end
  end
end

[Mantlepiece, Bookcase].each do |place|
  puts place.name
  puts place.constants.inspect
  puts place::Things.constants.inspect
end

# Output:
# Mantlepiece
# [:Things]
# [:Ornament]
# Bookcase
# [:Things]
# [:Hardback, :Paperback]

You can see that it Mantlepiecenests correctly Mantlepiece::Things::Ornament; but a class declaration Thingsfor Bookcasemeans that it Bookcase::Thingscontains only Hardbackand Paperback. Bookcase::Things::Ornamentmissing.

, Bookcase has_ornament, Things ?

+4
1

, , ( ). , Things; Things, Bookcase, module Things.

def has_ornament
  const_set(:Things, Module.new) unless const_defined? :Things, false
  self::Things.include OrnamentThings
end

module OrnamentThings
  class Ornament
  end
end

, Ruby , , . has_ornament Things , , . has_ornament , , (false , Things ).

+2

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


All Articles