Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add a constant value to a Ruby instance

Tags:

ruby

rspec

I'm testing a module (Foo::Api::Utility) by creating a dummy instance. The module references a constant that has been defined by the class that includes it (self.class::BASE_URL).

I'd like to be able to access this value and set it.

This doesn't work:

before(:each) do
  @utility = Object.new
  @utility.extend(Foo::Api::Utility)
  @utility.const_set('BASE_URL','https://domain.tld/api/v1')
end

What's the correct way to do this?

like image 725
craig Avatar asked Apr 24 '26 00:04

craig


1 Answers

What about:

before(:each) do
  @utility_class = Class.new
  @utility_class.include(Foo::Api::Utility)
  @utility_class.const_set('BASE_URL','https://domain.tld/api/v1')
  @utility = @utility_class.new
end

Or, in more succinct manner:

before(:each) do
  @utility =
    Class.new do
      include Foo::Api::Utility
      const_set :BASE_URL,'https://domain.tld/api/v1'
    end.new
end
like image 150
Marcin Kołodziej Avatar answered Apr 29 '26 21:04

Marcin Kołodziej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!