我有两个班级:
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类中使用基于设备类型的end_point URL?
此致 Kayen
答案 0 :(得分: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
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