chaining calls to method_missing ?

Hello Rubyists,

I am wondering if it's possible to chain calls to method missing.

Here's the scenario: I want to access a set of different version apis, for
one of two possible test environments. If we call the module VersionHelper,
I'd like to look something like this:

VersionHelper.payment.staging

and that would end up constructing a url something like

http://staging.mycompany.com/payment/api/version

I can do that with the *first* element in the chain and method missing. So
I can do VersionHelper.payment. But is it possible to do *two subsequent*
calls ? My code right now looks like so:

  module VersionHelper
    class << self
      def gv(microsite)
       ep = "http://#{test_environment}.
mycompany.com/#{microsite}/api/version"
      end
      def method_missing(microsite)
        gv(microsite)
      end
    end
  end

VersionHelper.payment works, but VersionHelper.payment.staging returns an
error along the lines of "method missing for <string>".

Thanks !!

···

--
A musician must make music, an artist must paint, a poet must write, if he
is to be ultimately at peace with himself.
- Abraham Maslow

Yes. Though, in your case, you return a String, so you would need to create a method_missing method on String, or...

Hey, it's Ruby! You can subclass String!

module VersionHelper
class << self
def gv(microsite)
ep = UrlString.new("http://#{test_environment}.mycompany.com/#{microsite}/api/version <mycompany.com)
end
def method_missing(microsite)
gv(microsite)
end
end
end

class UrlString < String
def method_missing(method)
UrlString.new(sub(%r{/.*?\.}, "/#{method}."))
end
end

···

On 6/10/22 07:14, Sean Felipe Wolfe wrote:

Hello Rubyists,

I am wondering if it's possible to chain calls to method missing.

Here's the scenario: I want to access a set of different version apis, for one of two possible test environments. If we call the module VersionHelper, I'd like to look something like this:

VersionHelper.payment.staging

and that would end up constructing a url something like

http://staging.mycompany.com/payment/api/version

I can do that with the *first* element in the chain and method missing. So I can do VersionHelper.payment. But is it possible to do *two subsequent* calls ? My code right now looks like so:

module VersionHelper
class << self
def gv(microsite)
ep = "http://#{test_environment}.mycompany.com/#{microsite}/api/version <mycompany.com;
end
def method_missing(microsite)
gv(microsite)
end
end
end

VersionHelper.payment works, but VersionHelper.payment.staging returns an error along the lines of "method missing for <string>".

Thanks !!

--
A musician must make music, an artist must paint, a poet must write, if he is to be ultimately at peace with himself.
- Abraham Maslow

Unsubscribe: <mailto:ruby-talk-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk&gt;