我有一个名为的脚本import.rb,它将从 url 导入 json 内容到 jekyll 中的草稿目录。下面是我的代码。
require 'fileutils'
require 'json'
require 'open-uri'
# Load JSON data from source
# (Assuming the data source is a json file on your file system)
data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec'))
# Proceed to create post files if the value array is not empty
array = data["user"]
if array && !array.empty?
# create the `_drafts` directory if it doesn't exist already
drafts_dir = File.expand_path('./_drafts', __dir__)
FileUtils.mkdir_p(drafts_dir) unless Dir.exist?(drafts_dir)
# iterate through the array and generate draft-files for each entry
# where entry.first will be the "content" and entry.last the "title"
array.each do |entry|
File.open(File.join(drafts_dir, entry.last), 'wb') do |draft|
draft.puts("---\n---\n\n#{entry.first}")
end
end
end
Run Code Online (Sandbox Code Playgroud)
当我运行时,ruby _scripts/import.rb我收到类似的错误
3: from _scripts/import.rb:7:in `<main>'
2: from /usr/lib/ruby/2.5.0/json/common.rb:156:in `parse'
1: from /usr/lib/ruby/2.5.0/json/common.rb:156:in `new'
/usr/lib/ruby/2.5.0/json/common.rb:156:in `initialize': no implicit conversion of StringIO into String (TypeError)
Run Code Online (Sandbox Code Playgroud)
请提出更正建议。
改变这个:
data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec'))
Run Code Online (Sandbox Code Playgroud)
对此:
data = JSON.parse(open('https://script.google.com/macros/s/AKfycbyHFt1Yz96q91-D6eP4uWtRCcF_lzG2WM-sjrpZIr3s02HrICBQ/exec').string)
Run Code Online (Sandbox Code Playgroud)
该.string方法Returns underlying String object。
当你在做的时候,改变这个:
array && !array.empty?
Run Code Online (Sandbox Code Playgroud)
对此:
array&.any?
Run Code Online (Sandbox Code Playgroud)
&.是安全导航操作符,它简化了检查nil和调用对象方法的过程。而从风格的角度来看,它的首选调用array.any?了!array.empty?。
最后,在使用时FileUtils.mkdir_p您不必包含保护条件unless Dir.exist?(drafts_dir)。可以安全地调用它,而不必担心它会删除或覆盖现有目录。