-5

我有两节课:

class Ios 
  REST_ENDPOINT = 'http://rest'
  SOAP_ENDPOINT = 'http://soap'
end

class Android
  REST_ENDPOINT = 'http://rest'
  SOAP_ENDPOINT = 'http://soap'
end

然后我有两个用于 REST 和 SOAP 的类:

class REST
  def some_action
    # I want to use the endpoint based on device type
  end
end


class SOAP
  def some_action
    # I want to use the endpoint based on device type 
  end
end

如何在 REST 和 SOAP 类中使用基于设备类型的端点 URL?

问候,凯恩

4

1 回答 1

3

这是你想要达到的目标吗?

class REST
  def some_action
    ios_url = URI.parse("#{Ios::REST_ENDPOINT}/login")
    android_url = URI.parse("#{Android::REST_ENDPOINT}/login")
  end
end

class SOAP
  def some_action
    ios_url = URI.parse("#{Ios::SOAP_ENDPOINT}/login")
    android_url = URI.parse("#{Android::SOAP_ENDPOINT}/login")
  end
end

你也可以像这样使用一些重构:

米信

module Endpoints

  def initialize device = Ios
    @device = device_class(device)
  end

  def url device = nil
    URI.parse "#{endpoint(device || @device)}/login"
  end

  def ios_url
    URI.parse "#{endpoint Ios}/login"
  end

  def android_url
    URI.parse "#{endpoint Android}/login"
  end

  private
  def endpoint device
    device_class(device).const_get self.class.name + '_ENDPOINT'
  end

  def device_class device
    device.is_a?(Class) ? 
      device : 
      Object.const_get(device.to_s.capitalize)
  end

end

在你的课程中包含 Mixin

class REST
  include Endpoints

  def some_action
    # use ios_url and android_url here
  end
end

class SOAP
  include Endpoints

  def some_action
    # use ios_url and android_url here
  end
end

一些测试:

puts REST.new(:Ios).url
#=> http://ios-rest.com/login

puts REST.new.url :Ios
#=> http://ios-rest.com/login

puts REST.new.ios_url
#=> http://ios-rest.com/login


puts REST.new(:Android).url
#=> http://android-rest.com/login

puts REST.new.url :Android
#=> http://android-rest.com/login

puts SOAP.new.android_url
#=> http://android-soap.com/login

是一个工作演示

于 2012-11-25T14:36:50.027 回答