Ruby get directory path of Subclass

26 Aug 2020

Sometimes you want to get the directory path of Subclas like this:

# /home/ubuntu/app/base.rb
class Base
  def dir_path
    File.expand_path(__dir__)
  end
end

# /home/ubuntu/app/test/action.rb
class Action < Base
end

Base.new.dir_path
#=> /home/ubuntu/app
Action.new.dir_path
#=> /home/ubuntu/app

You can see the __dir__ path is not change in the subclass.

After some research I found a solution:

# /home/ubuntu/app/base.rb
class Base
  class << self
    attr_accessor :_current_folder

    def inherited(klass)
      file_location = caller_locations.first.absolute_path
      klass._current_folder = Pathname.new(file_location).dirname
      super
    end
  end

  def dir_path
    self.class._current_folder
  end
end

# /home/ubuntu/app/test/action.rb
class Action < Base
end

Action.new.dir_path
#=> /home/ubuntu/app/test
Back to top