Youtube Data API Making a comment (Ruby) - ruby

I'm currently trying to create a new thread using the Youtube API. Here is the example provided:
def comments_insert(service, properties, part, **params)
resource = create_resource(properties) # See full sample for function
params = params.delete_if { |p, v| v == ''}
response = service.insert_comment(part, resource, params)
end
comments_insert(service,
{'snippet.parent_id': 'pS16m0FttKk',
'snippet.text_original': ''},
'snippet')
I'm essentially using their exact sample code but I'm getting an error that reads: ArgumentError - unknown keyword: snippet:
resource = ChannelbackController.create_resource({'snippet.parentId': '123', 'snippet.textOriginal': message})
response = service.insert_comment('snippet', resource).inspect

Related

How to get image classification prediction from GCP AIPlatform in ruby?

I'm new with ruby and I want to use GCP AIPlatform but I'm struggeling with the payload.
So far, I have :
client = ::Google::Cloud::AIPlatform::V1::PredictionService::Client.new do |config|
config.endpoint = "#{location}-aiplatform.googleapis.com"
end
img = File.open(imgPath, 'rb') do |img|
'data:image/png;base64,' + Base64.strict_encode64(img.read)
end
instance = Instance.new(:content => img)
request = Google::Cloud::AIPlatform::V1::PredictRequest.new(
endpoint: "projects/#{project}/locations/#{location}/endpoints/#{endpoint}",
instances: [instance]
)
result = client.predict request
p result
Here is my proto
message Instance {
required bytes content = 1;
};
But I have the following error : Invalid type Instance to assign to submessage field 'instances'
I read the documentation but for ruby SDK it's a bit light.
The parameters are OK, the JS example here : https://github.com/googleapis/nodejs-ai-platform/blob/main/samples/predict-image-object-detection.js is working with those parameters
What am I doing wrong ?
I managed it
client = Google::Cloud::AIPlatform::V1::PredictionService::Client.new do |config|
config.endpoint = "#{location}-aiplatform.googleapis.com"
end
img = File.open(imgPath, 'rb') do |img|
Base64.strict_encode64(img.read)
end
instance = Google::Protobuf::Value.new(:struct_value => {:fields => {
:content => {:string_value => img}
}})
endpoint = "projects/#{project}/locations/#{location}/endpoints/#{endpoint}"
request = Google::Cloud::AIPlatform::V1::PredictRequest.new(
endpoint: endpoint,
instances: [instance]
)
result = client.predict request
p result
The use of the Google::Protobuf::Value looks ugly to me but it works

Ruby Strong Params: NoMethodError undefined method permit for Integer

My controller:
class V1::SendContractController < V1::BaseController
def create
byebug
bride_membership = Wedding.find(send_params[:weddingId]).bride_memberships[0]
SendBrideContractJob.perform_now(bride_membership, send_params[:contractId])
render json: { enqueuedDelivery: true }, status: :ok
end
private
def send_params
params
.require(:weddingId)
.permit(:contractId)
end
end
My params
Parameters: {"weddingId"=>4, "contractId"=>20, "send_contract"=>{"weddingId"=>4, "contractId"=>20}}
The error
NoMethodError (undefined method `permit' for 4:Integer):
But then when I byebug it I get what I want!
(byebug) params
<ActionController::Parameters {"weddingId"=>4, "contractId"=>20, "controller"=>"v1/send_contract", "action"=>"create", "send_contract"=>{"weddingId"=>4, "contractId"=>20}} permitted: false>
(byebug) params[:weddingId]
4
And I'm using axios with an interceptor to take care of formatting issues:
axios.interceptors.request.use((config) => {
if(config.url !== "/authentications") {
config.paramsSerializer = params => {
// Qs is already included in the Axios package
return qs.stringify(params, {
arrayFormat: "brackets",
encode: false
});
};
axios.defaults.headers.common['Authorization'] = `Bearer ${store.state.token.token}`
config.headers.common['Authorization']= `Bearer ${store.state.token.token}`
axios.defaults.headers.common['Accept'] = 'application/vnd.bella.v1+json'
config.headers.common['Accept'] = 'application/vnd.bella.v1+json'
return config
}
return config
})
I believe that require gives you the object at the key you provide to do further permit and / or require calls.
Perhaps you could try (not tested):
params.require(:weddingId)
params.permit(:weddingId, :contractId)
Edit: there's this too: Multiple require & permit strong parameters rails 4
Refer to this documentation and question.The require ensures that a parameter is present. If it's present, returns the parameter at the given key, otherwise raises an ActionController::ParameterMissing error.
p = { "weddingId"=>4, "contractId"=>20 }
ActionController::Parameters.new(p).require(:weddingId)
# 4
p = { "weddingId"=>nil, "contractId"=>20 }
ActionController::Parameters.new(p).require(:weddingId)
# ActionController::ParameterMissing: param is missing or the value is empty: weddingId
If you want to make sure :weddingId is present:
def contract_params
params.require(:weddingId)
params.permit(:contractId, :weddingId)
end
BTW, SendContractController is better called ContractsController.

elasticsearch_dsl TypeError: index() missing 1 required positional argument: 'doc_type'

class Article(Document):
title = Text(analyzer='snowball', fields={'raw': Keyword()})
body = Text(analyzer='snowball')
tags = Keyword()
published_from = Date()
lines = Integer()
class Index:
name = 'blog45'
settings = {
"number_of_shards": 2,
}
def save(self, ** kwargs):
self.lines = len(self.body.split())
return super(Article, self).save(** kwargs)
def is_published(self):
return datetime.now() >= self.published_from
# create the mappings in elasticsearch
Article.init()
# create and save and article
article = Article(meta={'id': 42}, title='Hello world!', tags=['test'])
article.body = ''' looong text '''
article.published_from = datetime.now()
article.save() ### BOMBS HERE!!! ###
My save() always throws the error:
TypeError: index() missing 1 required positional argument: 'doc_type'
The example above was taken from the documentation but does not work correctly. How can I specify the [doc_type]?
In elasticsearch-py, its
res = elastic_client.index(index="bb8_index", body=doc, doc_type='_doc')
As of 2/1/2020:
I would avoid using the elasticsearch_dsl library as it isn't able to save/index a document to Elasticsearch. The library is not compatible with the latest Elasticsearch (7.5+).
Use the regular elasticsearch-py library

Post to Sinatra API with hyperresource

I built an app in Sinatra with Roar (hal/JSON) and now I'm trying to post a new item from my client to this API.
In my Sinatra app I have routes like these:
get '/todos/new' do
#pagetitle = 'New Todo'
#todo = Todo.new
#todo.extend(TodoRepresenter)
#todo.to_json
erb :'todos/new'
end
post "/todos" do
#todo = Todo.new(params[:todo])
if #todo.save
redirect "todos/#{#todo.id}"
else
erb :"todos/new"
end
end
And my client.rb looks like this:
require 'hyperresource'
class ApiRequest < HyperResource
api = ApiRequest.new(root: 'http://127.0.0.1:9393',
headers: {'Accept' => 'application/vnd.http://127.0.0.1:9393.v1+json'})
api.post '/todos/new', { :title => "a"}
This doesn't work. The only way of get a working client is the get function:
require 'hyperresource'
class ApiRequest < HyperResource
api = ApiRequest.new(root: 'http://127.0.0.1:9393/todos/13',
headers: {'Accept' => 'application/vnd.http://127.0.0.1:9393.v1+json'})
todo = api.get
output = todo.body
puts output
I don't know how to solve this, and the Github page doesn't tell me either.
I changed the API slightly:
get '/todos' do
#pagetitle = 'New Todo'
#todo = Todo.new
erb :'todos/new'
end
post "/todos/new" do
#todo = Todo.new(params[:todo])
#todo.extend(TodoRepresenter)
#todo.to_json
if #todo.save
redirect "todos/#{#todo.id}"
else
erb :"todos/new"
end
end
and also the way of posting in my client:
todo = api.get.new_todo.post(title: "Test")
In my API console I now get:
D, [2014-11-04T17:11:41.875218 #11111] DEBUG -- : Todo Load (0.1ms) SELECT "todos".* FROM "todos" WHERE "todos"."id" = ? LIMIT 1 [["id", 0]]
ActiveRecord::RecordNotFound - Couldn't find Todo with 'id'=new:
and a lot of other code.
In my client console I get a lot of code, with a hyper resource server error and a lot of other code.

How Do I Get Response Headers From ActiveResource?

I'm using ActiveResource 4.0, and I need to get pagination working. I've set the response headers on the server end, but I cannot read them on the client end.
I'm using this great blog post:
http://javiersaldana.com/2013/04/29/pagination-with-activeresource.html
And I'm trying to read the headers from the response:
ActiveResource::Base.connection.response
But I'm getting this error:
undefined method 'response' for #<ActiveResource::Connection:0x007f9a4f9692b8>
How can I get the response headers?
gem "activeresource-response" to the rescue .
https://github.com/Fivell/activeresource-response
Example, lets say server returns headers for pagination
X-limit,X-offset,X-total
class Order < ActiveResource::Base
self.format = :json
self.site = 'http://0.0.0.0:3000/'
self.element_name = "order"
add_response_method :http_response # our new method for returned objects
end
class OrdersController < ApplicationController
def index
orders = Order.all(:params=>params)
#orders = Kaminari::PaginatableArray.new(
orders,{
:limit => orders.http_response['X-limit'].to_i,
:offset =>orders.http_response['X-offset'].to_i,
:total_count => orders.http_response['X-total'].to_i
})
end
end

Resources