4
我試圖設置我們的CRM系統以在添加特定類型的記錄(列表)時在wordpress中創建帖子。TypeError:沒有將nil隱式轉換爲字符串錯誤
我發現這個tutorial,我正在軌道控制檯中測試它。
我的班級:
require 'rubygems'
require 'open-uri'
require 'json'
require 'net/http'
# Please note that the vanilla wp-json-api plugin does not support user authentication for create_post.
# Check out my fork for authentication support: https://github.com/Achillefs/wp-json-api
class Listing
API_URI = 'http://my_wp_url/api/'
API_USER = 'my_username'
API_PASS = 'my_password'
attr_accessor :title, :address, :sell_price, :type
def initialize(opts = {})
# set all values if valid
opts.each do |key,val|
begin
self.send(:"#{key}=",val)
rescue NoMethodError => e
raise ArgumentError("#{key} is not a valid listing attribute")
end
end
self.type = 'post' if self.type == nil
end
def publish!
# Need to get a nonce token from WP in order to create a post
nonce_response = JSON.parse(open(API_URI + "get_nonce/?controller=posts&method=create_post").read)
if nonce_response['status'] == 'ok'
nonce = nonce_response['nonce']
url = URI.parse(API_URI + "posts/create_post")
args = {
'nonce' => nonce, 'author' => API_USER, 'user_password' => API_PASS,
'status' => 'draft', 'title' => self.title
}
resp, data = Net::HTTP.post_form(url, args)
response = JSON.parse(data)
if response['status'] == 'ok'
puts response.inspect
else
raise response['error'].to_s
end
else
raise nonce_response['error'].to_s
end
end
end
並在控制檯輸出如下
2.0.0-p353 :001 > require 'listing'
=> true
2.0.0-p353 :002 > l = Listing.new(:title => "test")
=> #<Listing:0x007fab9286a2c8 @title="test", @type="post">
2.0.0-p353 :003 > l.publish!
TypeError: no implicit conversion of nil into String
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/json-1.8.1/lib/json/common.rb:155:in `initialize'
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/json-1.8.1/lib/json/common.rb:155:in `new'
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/json-1.8.1/lib/json/common.rb:155:in `parse'
from /Users/Nick/rails_projects/wp_api/lib/listing.rb:38:in `publish!'
from (irb):3
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
from /Users/Nick/.rvm/gems/[email protected]_rails_4_0/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
2.0.0-p353 :004 >
38號線是這個
response = JSON.parse(data)
所以我想我得到沒有迴應。我對此相對較新,不確定如何打破原因。
在此先感謝您的幫助。
尼克