How do I call object methods from a static method in the ruby ​​class?

From academic / "for the sake of interests" (best practice):

In the Ruby class, I want to provide a static method that calls the methods of an instance of the class. Is this an acceptable way to do this, or is there a "better" way?

class MyUtil
    def apiClient
      @apiClient ||= begin
         apiClient = Vendor::API::Client.new("mykey")
      end
    end

    def self.setUpSomething(param1, param2, param3=nil)
      util = self.new() # <-- is this ok?
      util.apiClient.call("foo", param2)
      # some logic and more util.apiClient.calls() re-use client.
    end
end

And then I can easily use this lib:

MyUtil.setUpSomething("yes","blue")

vs

MyUtil.new().setupUpSomething()
# or
util = MyUtil.new()
util.setUpSomething()

Environment - these are sys admin scripts that are executed in a controlled manner, 1 call at a time (i.e. not a webapp type that can be subject to high load).

+4
source share
3 answers

In this particular case, you probably need a class instance variable:

class MyUtil
  @apiClient = Vendor::API::Client.new("mykey")

  def self.setUpSomething(param1, param2, param3=nil)
    @apiClient.call("foo", param2)
    # some logic and more util.apiClient.calls() re-use client.
  end
end

If you need a lazy instance, use an accessor:

class MyUtil
  class << self
    def api_client
      @apiClient ||= Vendor::API::Client.new("mykey")
    end

    def setUpSomething(param1, param2, param3=nil)
      apiClient.call("foo", param2)
      # some logic and more util.apiClient.calls() re-use client.
    end
  end
end
+2
source

, , - :

class MyUtil
  API_KEY = "mykey"

  def apiClient
    @apiClient 
  end

  def initialize
    @apiClient = Vendor::API::Client.new(API_KEY)
    yield self if block_given?
  end

  class << self

    def setUpSomthing(arg1,arg2,arg3=nil)
        self.new do |util|
            #setup logic goes here
        end     
    end

    def api_call(arg1,arg2,arg3)
        util = setUpSomthing(arg1,arg2,arg3)
        util.apiClient.call("foo", param2)
        #do other stuff
    end

  end

end

, setUpSomthing , , .

setUpSomthing , , , .

+2

Bret, what do you think of this:

class MyUtil
  API_KEY = 'SECRET'

  def do_something(data)
    api_client.foo(data)
  end

  def do_something_else(data)
    api_client.foo(data)
    api_client.bar(data)
  end

  private

  def api_client
    @api_client ||= Vendor::API::Client.new(API_KEY)
  end
end

Using

s = MyUtil.new
s.do_something('Example') # First call
s.do_something_else('Example 2')
0
source

Source: https://habr.com/ru/post/1681103/


All Articles