craig
craig

Reputation: 26262

Access a constant defined in class from a mixin included in the class

I have a mixin (Api::Utility) that is referenced by two classes: Api::Utility::One::WorkstationClient and Api::Utility::Two::WorkstationClient. Both classes define a constant, BASE_URL, that I'd like to access in the mixin. When I attempt to access the constant, I get an error that reads `NameError (uninitialized constant Epic::Api::Utility::BASE_URL).

#!/usr/bin/env ruby

module Api

  class WorkstationClientFactory

    def self.create_client(version = :v2)
      case version
      when :v2
        Two::WorkstationClient.new()
      when :v1
        One::WorkstationClient.new()
      else
        raise ArgumentError, "'#{version.inspect}' is not a valid version symbol.  Valid: [:v1|:v2]."
      end
    end

  end # /WorkstationClientFactory

  # Api::Utility
  module Utility
    def bar
      puts "BASE_URL: #{BASE_URL}"
    end
  end

  module One
    # Api::One::WorkstationClient
    class WorkstationClient
      include Api::Utility

      BASE_URL = 'https://domain.tld/api/v1'

      def initialize()
        puts "Creating #{self.class.name}"
      end

    end # /WorkstationClient
  end # One

  module Two
    # Api::Two::WorkstationClient
    class WorkstationClient
      include Api::Utility

      BASE_URL = 'https://domain.tld/api/v2'

      def initialize()
        puts "Creating #{self.class.name}"
      end

    end # /WorkstationClient
  end # /Two

end # /module

v1 = Api::WorkstationClientFactory.create_client(:v1)
v1.bar <-- error here
BASE_URL: https://domain.tld/api/v1  <-- desired result

v2 = Api::WorkstationClientFactory.create_client(:v2)
v2.bar <-- error here
BASE_URL: https://domain.tld/api/v2  <-- desired result

What's the right way to access the BASE_URL in the mixin, in this situation?

Upvotes: 2

Views: 457

Answers (1)

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

You can use self.class::BASE_URL.

Upvotes: 4

Related Questions