Have a parent class's method access the subclass's constants

前端 未结 5 813
闹比i
闹比i 2021-02-12 03:56

For example:

class Animal

 def make_noise
    print NOISE
 end

end

class Dog < Animal
    NOISE = \"bark\"
end

d = Dog.new
d.make_noise # I want this to p         


        
5条回答
  •  北海茫月
    2021-02-12 04:24

    If you're doing this to configure your sub classes so that the base class has access to the constants then you can create a DSL for them like this:

    module KlassConfig
      def attr_config(attribute)
        define_singleton_method(attribute) do |*args|
          method_name = "config_#{attribute}"
          define_singleton_method method_name do
            args.first
          end
          define_method method_name do
            args.first
          end
        end
      end
    end
    
    class Animal
      extend KlassConfig
      attr_config :noise
    
      def make_noise
        puts config_noise
      end
    end
    
    class Dog < Animal
      noise 'bark'
    end
    

    This way is a bit more performant as on each method call you don't have to introspect the class to reach back (or is it forward?) for the constant.

提交回复
热议问题