[英]Ruby calling object as an attribute inside another object
我有這樣的事情:
d1 = RequestService.new('env', 'user', 'password')
req_obj = d1.getRequest('0000-0000')
d1.addAttachment(req_obj, 'file_location')
似乎無法正常工作。 d1.addAttachment
沒有使用req_obj
。 如果我執行d1.addAttachment('000-000','file_location'),則它可以完美運行。 如果我將req_obj用作addAttachment內的屬性,它將失敗並顯示錯誤:
request.rb:67:in `+': no implicit conversion of Request into String (TypeError)
from request.rb:67:in `addAttachment'
from tes.rb:9:in `<main>'
代碼是:
class Request
def initialize(id)
$id = id
end
def to_s
$id.chomp
end
end
class RequestService < WsApi
def initialize(environment, user, password)
@environment = environment
@user = user
@password = password
if @environment == 'staging'
@uri = 'some url'
elsif @environment == 'production'
@uri = ''
else
puts 'Enter valid environment - staging / production'
end
end
def getRequest(request_id)
# define local variables
req_id = request_id
begin
# Create object of ws_api_base class to do a get function on the request_id to check if id exists or not
obj1 = WsApi.new(@uri, @user, @password)
restap = obj1.restapi
response = restap['requests/' + req_id ].get(:username => @user, :password => @password, :accept => 'application/json')
# Create a request object to set request id as valid cx ticket number
if response.code === 200
req_obj = Request.new(req_id)
return req_obj
end
rescue
puts 'Request id ' + req_id + ' does not exists'
exit
end
end
def addAttachment(request_id, file_location)
# define local variables
req_id = request_id
file_loc = file_location
# If request exists proceed with add attachment
f = Base64.encode64(File.read(file_loc))
file_size = File.size(file_loc)
file_name = File.basename(file_loc)
payload = [{"contentType" => "text/plain","size" => file_size,"fileName" => file_name,"data" => f.chomp}].to_json
obj1 = WsApi.new(@uri, @user, @password)
restap = obj1.restapi
response = restap['requests/' + req_id + '/attachments'].post(payload, :username => @user, :password => @password, :content_type => 'application/json', :accept => 'application/json')
if response.code === 200
puts "Attachment added successfuly"
else
puts response
end
end
end
addAttachment
期望String不是對象,您只需要在req_object
上調用to_s
方法。 Ruby不會為您這樣做。
您可以使用"requests/#{req_id}/attachments"
代替使用'requests/' + req_id + '/attachments'
。 也許您應該覆蓋to_s
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.