Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Accessing calling child class constants from parent class?

Tags:

oop

ruby

In Ruby, how can I access the calling class's constants from a parent class?

Module Foo
  class Base
    def test()
      #how do I access calling class's constants here?
      #ex: CallingClass.SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end
like image 520
doremi Avatar asked Dec 12 '22 03:12

doremi


1 Answers

This seems to work - it forces constant lookup to scope into the current instance's class

module Foo
  class Base
    def test
      self.class::SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end

Bar.new.test # => 'test'
like image 61
Nikita Chernov Avatar answered Apr 30 '23 23:04

Nikita Chernov