Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby nested classes and modules

Tags:

ruby

I am familiar with the concept of nesting classes and modules within another module and grouping them in a namespace. What is the idea / purpose behind

  1. Nesting classes within another class

    class A
      class B
        def method_B
          ...
        end
      end
    end
    
  2. Nesting modules within another class

    class A
      module c
        def method_c
          ...
        end
      end
    end
    

thanks, ash

like image 863
user290870 Avatar asked Sep 12 '26 22:09

user290870


2 Answers

Classes are also namespaces, so it's the same idea. Class is a subclass of Module, so if you get it in the context of modules, you also get it in the context of classes.

like image 116
Chuck Avatar answered Sep 15 '26 11:09

Chuck


It is all about grouping related concerns while exposing sensible semantics. As an example of number 1 an HTTP::Request (Request class embedded in a larger HTTP protocol class) is a quite different thing from an FTP::Request. With modules it enables the common ruby idiom of Behavior::InstanceMethods and Behavior::ClassMethods for handling mixins.

like image 28
Ben Hughes Avatar answered Sep 15 '26 11:09

Ben Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!