Mongoid
Mongoid

Reputation: 97

Creating a REST service client

I m trying to create a rest service client as a service. Here is my service:

version 1

class MyService
  def self.call(method_name, *args)
    send(method_name, args)
  end
  
  def useful_method
    'id, name'
  end

  # some methods below
end

This does not work when I try to invoke methods without any arguments. For example, this:

MyService.call(:useful_method)

fails because useful_method does not expect arguments. Most of my methods have arguments, so this will work in most cases.

I tried this version as well:

version 2

class MyService
  def self.call(*args)
    send(args)
  end
  
  def useful_method
    'id, name'
  end

  # some methods below
end

But this does not seem to work for any method with or without arguments.

How can I create something like this that passes method_name followed by arguments or no arguments depending on whether the method has arguments?

I think I've seen this here, but I can't find the source for this.

Question update

Here is the version 1 error I got :

irb(main):001:0> MyService.call(:useful_method)
ArgumentError: wrong number of arguments (given 1, expected 0)

Here is the version 2 error I got :

irb(main):001:0> MyService.call(:useful_method)
TypeError: [:useful_method] is not a symbol nor a string

Upvotes: 0

Views: 69

Answers (3)

mmsilviu
mmsilviu

Reputation: 1451

you can send params to send with `send(method_name, *args)

or

Defining the Service like this:

class MyService
  attr_reader :method_name, :args

  def initialize(options = {})
    # extract attributes
    method_name = options[:method_name] || default_value
    args = options[:args] || []
  end

  def call
    send(method_name, *args)
  end
end

and call the service MyService.new(method_name: 'useful_method', args: [staff]).call

Upvotes: 0

Leaf
Leaf

Reputation: 553

How about

class MyService
  def self.call(*args)
    send(*args)
  end

  class << self
    private 
    def useful_method
      'id, name'
    end
  end
end

Upvotes: 2

Muntasim
Muntasim

Reputation: 6786

You are trying to call some instance methods from class (static) method. You need call send to the instance of the class. This should work:

class MyService
  def self.call(method_name, *args)
    new.send(method_name, args)
  end

  def useful_method(*args)
    'id, name'
  end

  # some methods below
  end

Upvotes: 0

Related Questions