Search code examples
ruby-on-railsrubymetaprogramming

What extended do ruby


What extended does in this code?

class << self
    def extended(klass)
      klass.class_exec do
        define_method :supported_attrs do
          that_klass = self.class
          that_klass.const_defined?(:ATTRS) ? that_klass.const_get(:ATTRS) : []
        end
      end
    end
  end

https://github.com/lokalise/ruby-lokalise-api/blob/2d78458cbb16fa62d9f6018e79b7ea5da53b77f6/lib/ruby_lokalise_api/concerns/attrs_loadable.rb#L8

There is no use it in the project Only supported_attrs Where does Klass come from? There no mention extended in the project


Solution

  • So if you're not familiar with the extend function, the short version of it is that will add methods from the specified module into a class. When you call extend, the .extended method is called on the module, with the class as its parameter:

    module MyModule
      def self.extended(klass)
        p klass
      end
    end
    
    class MyClass
      extend MyModule
      # => Will print "MyClass"
    end
    

    So in your case, you can look for instances where the module is being extend'ed to find where those methods will be added.