※本記事は2019年3月21日現在の情報です。
RubyでGoogle Cloud Vision を試そうと、GCP公式サイトのサンプルを実施すると、
undefined method `new' for Google::Cloud::Vision:Module (NoMethodError)
というエラーが発生した。
参考にしたCloud Vision 公式サンプルコード
# project_id = "Your Google Cloud project ID"
# image_path = "Path to local image file, eg. './image.png'"
require "google/cloud/vision"
vision = Google::Cloud::Vision.new project: project_id
image = vision.image image_path
puts image.text
原因
Ruby クライアントの v0.32 から後方互換性のない仕様変更が入っていた
https://cloud.google.com/vision/docs/ruby-client-migration
サンプルコードも上記サイト内で紹介されている
Google::Cloud::Vision::ImageAnnotator を使うようになった。
image_annotator = Google::Cloud::Vision::ImageAnnotator.new
# The name of the image file to annotate
file_name = "./resources/cat.jpg"
response = image_annotator.text_detection(
image: image_path,
max_results: 1 # optional, defaults to 10
)
response.responses.each do |res|
res.text_annotations.each do |text|
puts text.description
end
end
ちなみに、公式ドキュメントの英語ページの方はサンプルも最新の情報に更新されていた。
https://cloud.google.com/vision/docs/detecting-text?hl=en#vision-text-detection-ruby
GCP公式の日本語ドキュメントは更新が遅いことが過去にもあったので、なにか詰まったら英語ページを確認するのが吉。