【问题标题】:Ruby: Dynamically defining classes based on user inputRuby:根据用户输入动态定义类
【发布时间】:2011-07-04 16:21:11
【问题描述】:

我正在用 Ruby 创建一个库,允许用户访问外部 API。可以通过 SOAP 或 REST API 访问该 API。我想支持两者。

我首先在不同的模块中定义了必要的对象。例如:

soap_connecton = Library::Soap::Connection.new(username, password)
response = soap_connection.create Library::Soap::LibraryObject.new(type, data, etc)
puts response.class # Library::Soap::Response

rest_connecton = Library::Rest::Connection.new(username, password)
response = rest_connection.create Library::Rest::LibraryObject.new(type, data, etc)
puts response.class # Library::Rest::Response

我想做的是允许用户指定他们只希望使用其中一个 API,可能是这样的:

Library::Modes.set_mode(Library::Modes::Rest)
rest_connection = Library::Connection.new(username, password)
response = rest_connection.create Library::LibraryObject.new(type, data, etc)
puts response.class # Library::Response

但是,我还没有找到一种方法来动态设置,例如,基于Library::Modes.set_mode 的输入,Library::Connection。实现此功能的最佳方式是什么?

【问题讨论】:

    标签: ruby class dynamic


    【解决方案1】:

    墨菲定律盛行;将问题发布到 Stack Overflow 后立即找到答案。

    这段代码似乎对我有用:

    module Library
      class Modes
        Rest = 1
        Soap = 2
    
        def self.set_mode(mode)
          case mode
          when Rest
            Library.const_set "Connection", Class.new(Library::Rest::Connection)
            Library.const_set "LibraryObject", Class.new(Library::Rest::LibraryObject)
          when Soap
            Library.const_set "Connection", Class.new(Library::Soap::Connection)
            Library.const_set "LibraryObject", Class.new(Library::Soap::LibraryObject)
          else
            throw "#{mode.to_s} is not a valid Library::Mode"
          end
        end
      end
    end
    

    快速测试:

    Library::Modes.set_mode(Library::Modes::Rest)
    puts Library::Connection.class == Library::Rest::Connection.class # true
    c = Library::Connection.new(username, password)
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 2019-04-18
      • 2015-03-03
      • 2020-07-02
      相关资源
      最近更新 更多