【发布时间】:2020-07-04 02:07:56
【问题描述】:
出于测试和管理目的,我希望构建一个类来与 API 进行通信。我已经关闭了连接和身份验证,但正在努力解决类的基本结构和大小。
我的主要目标是保持每个应用程序域的拆分,但仍然可以通过一个类/连接轻松访问。 我已经做了一个更简单的例子来说明我正在寻找的东西。实际上,每个域都有自己的一组业务规则要遵循,这就是为什么我想将它们分开,而 API 连接保持不变。
例如,在 CLI 级别我想调用:
$ client_one = Api.new("one")
$ client_two = Api.new("two")
$ client_one.Bikes.delete(1)
> deleted bike 1 from one
$ client_two.Phones.new(phone)
> posted phone iPhone to two
我的想法是将模块嵌套在 Api 类中,但我无法让它工作或找到正确的语法。
class Api
def initialize(client)
@client = client
@connection = Authentication.get_connection(@client)
end
#preferable put each submodule in a separate file
module Authentication
def get_connection(client)
#code to get Faraday connection
end
end
module Bikes
def new(object)
#code to post new bike
@connection.post(object)
puts "posted bike #{object.name} to #{@client}"
end
def delete(id)
#code to delete old bike
@connection.delete(id)
puts "deleted bike #{id} from #{@client}"
end
end
module Phones
def new(object)
#code to post new phone
@connection.post(object)
puts "posted phone #{object.name} to #{@client}"
end
end
end
这会导致如下错误:
NoMethodError: undefined method `Bikes' for #<Api:0x0000000003a543a0>
是否有可能实现我的目标,还是有更好的“Ruby”方法来实现它?
此外,是否可以将子模块拆分为不同的文件?例如:
api.rb
modules
+ -- authentication.rb
+ -- bikes.rb
+ -- phones.rb
【问题讨论】:
标签: ruby