-5

私は2つのクラスを持っています:

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

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

次に、REST と SOAP の 2 つのクラスがあります。

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 を使用するにはどうすればよいですか?

よろしく、カイエン

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 に答える