fog and dyn destroy record - ruby

I'm currently using Fog to manage Dyn DNS provider. According the documentation, there's a destroy method on the DNS record object. However, when I call destroy, on a record, nothing happens... the method just returns true, but it is never deleted. Here's the code I'm using:
#dynect = Fog::DNS.new(
:provider => "dynect",
:dynect_customer => "CUSTOMER",
:dynect_username => "USERNAME",
:dynect_password => 'PASSWORD'
)
#zone = #dynect.zones.get('zone.example.com')
#record = #zone.records.find{|r| r.name == 'master.zone.example.com' && r.type == 'CNAME'}
#record.destroy
#zone.save
This will return true, but nothing ever happens - the DNS record still exists on Dyn.
How do I delete a record with Fog and Dyn?

Turns out you need to then publish (not save) the zone... This is not obvious, since other providers, like AWS, don't require. Here's an updated code snippet:
#dynect = Fog::DNS.new(
:provider => "dynect",
:dynect_customer => "CUSTOMER",
:dynect_username => "USERNAME",
:dynect_password => 'PASSWORD'
)
#zone = #dynect.zones.get('zone.example.com')
#record = #zone.records.find{|r| r.name == 'master.zone.example.com' && r.type == 'CNAME'}
#record.destroy
#zone.publish # changed this

Related

In RubyZoho, how to set Task.related_to Lead.id?

I wrote this question up at RubyZoho's forum, but it's languishing there, and it's such a simple question it deserves a wider audience.
I have used RubyZoho to upload a new Lead record to the Zoho CRM API, and now I want to upload a Task with its "related to" field set to that Lead.
Configuring RubyZoho:
RubyZoho.configure do |config|
config.api_key = Setting.plugin_redmine_tigase['zoho_authorization_token']
config.crm_modules = [
'Leads',
'Tasks'
]
config.ignore_fields_with_bad_names = true
config.cache_fields = true
end
Creating the lead:
lead = RubyZoho::Crm::Lead.new
lead.first_name = splut.first
lead.last_name = splut.last
lead.full_name = params[:name]
lead.company = params[:company]
lead.email = params[:mail]
lead.description = description
lead.save
Creating the Task:
found = RubyZoho::Crm::Lead.find_by_email(params[:mail])
lead = found.first
task = RubyZoho::Crm::Task.new
task.related_to = lead.id
task.subject = params[:subject]
task.description = description
task.save
I tried task.related_to = lead.leadid, and got a Task record with a blank "related to" in the Zoho website. And when I try task.related_to = 'Lead'; task.relatedtoid = lead.leadid, I get a undefined method relatedtoid=, naturally because the variable has no setter.
So what am I missing? how do I do this simple thing?
If you look at the documentation it has a section on this
https://www.zoho.com/creator/help/script/creating-a-record-in-zoho-crm.html#create-lead
taskInfo = {
"Task Owner" : input.Owner_Name,
"SMOWNERID" : input.Owner_ID,
"Subject" : input.Subject,
"Description" : input.Description,
"SEMODULE" : "Accounts",
"SEID" : input.Account_ID,
"CONTACTID" : input.Contact_ID};
crmResp = zoho.crm.create("Tasks", taskInfo);
SMOWNERID is the ID of the Owner
SEMODULE can be Accounts or Leads or Cases
SEID is the ID of the Record given in the SEMODULE
CONTACTID is the ID of the contact record
Also if you look at the ruby_zoho_rspec for creating new task
https://github.com/amalc/rubyzoho/blob/950ffe369252f8fad3e7ae67ebddec859c84e19b/spec/ruby_zoho_spec.rb
it 'should save an task record related to an account' do
VCR.use_cassette 'zoho/task_related_to_account' do
a = RubyZoho::Crm::Account.all.first
e = RubyZoho::Crm::Task.new(
:task_owner => a.account_owner,
:subject => "Task should be related to #{a.account_name} #{Time.now}",
:description => 'Nothing',
:smownerid => "#{a.smownerid}",
:status => 'Not Started',
:priority => 'High',
:send_notification_email => 'False',
:due_date => '2014-02-16 16:00:00',
:start_datetime => Time.now.to_s[1, 19],
:end_datetime => '2014-02-16 16:00:00',
:related_to => "#{a.account_name}",
:seid => "#{a.accountid}",
:semodule => 'Accounts'
)
r_expected = e.save
r = RubyZoho::Crm::Task.find_by_activityid(r_expected.id)
r.first.subject[0..20].should eq(r_expected.subject[0..20])
end
So that should help you out link it by specifying SEMODULE and SEID

savon gem example_body not coming properly

I have a wsdl url to give request and get response this is my code(using savon gem for this)
client = Savon.new('http://services.chromedata.com/Description/7a?wsdl')
service = :Description7a
port = :Description7aPort
operation = :getDivisions
division = client.operation(service, port, operation)
I am able to print example_body like
division.example_body
=> {:DivisionsRequest=>{:accountInfo=>{:_number=>"string", :_secret=>"string", :_country=>"string", :_language=>"string", :_behalfOf=>"string"}, :_modelYear=>"int"}}
and i'm able to set values like
division.body = {.........}
other operation such like
operationlist = client.operations(service, port)
=> ["getVersionInfo", "getModelYears", "getDivisions", "getSubdivisions", "getModels", "getStyles", "describeVehicle", "getCategoryDefinitions", "getTechnicalSpecificationDefinitions"]
I used describe vehicle
desc_veh = client.operation(service, port, "describeVehicle")
whose example_body is like
desc_veh.example_body
=> {:VehicleDescriptionRequest=>{}}
so unable to set values for desc_veh.body and the use the .call function
I don know whether it is a savon gem problem or the wsdl url problem
Your code could look like this:
gem "savon", "~> 2.0"
require "savon"
client = Savon.client(
:wsdl => 'http://services.chromedata.com/Description/7a?wsdl',
:convert_request_keys_to => :camelcase,
:log => true,
:log_level => :debug,
:pretty_print_xml => true
)
res = client.call(:get_divisions,
message: { :param1 => 'value1', :param2 => 'value2' }
)
print res.to_hash
The parameters are simply a hash in key/value pairs.

How to update all fields in MailChimp API batch subscribe using Ruby and Gibbon

I am using Ruby 1.9.3 without Rails and version 1.0.4 of the Gibbon gem.
I have referrals populated with my list and can send the following to MailChimp with Gibbon. However, only the email address and email type fields are populated in the list in MailChimp. What am I doing wrong that is prohibiting all the merge fields from being imported via API?
Here is the batch and map of the list.
referrals.each_slice(3) do |batch|
begin
prepared_batch = batch.map do |referral|
{
:EMAIL => {:email => referral['client_email']},
:EMAIL_TYPE => 'html',
:MMERGE6 => referral['field_1'],
:MMERGE7 => referral['field_2'],
:MMERGE8 => referral['field_3'],
:MMERGE9 => referral['field_4'],
:MMERGE11 => referral['field_5'],
:MMERGE12 => referral['field_6'],
:MMERGE13 => referral['field_7'],
:MMERGE14 => referral['field_8'],
:MMERGE15 => referral['field_9'],
:FNAME => referral['client_first_name']
}
end
#log.info("prepared_batch : #{prepared_batch}")
result = #gibbon.lists.batch_subscribe(
:id => #mc_list_id,
:batch => prepared_batch,
:double_optin => false,
:update_existing => true
)
#log.info("#{result}")
rescue Exception => e
#log.warn("Unable to load batch into mailchimp because #{e.message}")
end
end
The above executes successfully. However, only the email address and email type are populated but most of the fields should be populated.
Here is my log output for one of the prepared_batches. I replaced the real values with Value. I used my own email for testing.
I, [2013-11-11T09:01:14.778907 #70827] INFO -- : prepared_batch : [{:EMAIL=>
{:email=>"jason+6#marketingscience.co"}, :EMAIL_TYPE=>"html", :MMERGE6=>"Value",
:MMERGE7=>"Value", :MMERGE8=>nil, :MMERGE9=>nil, :MMERGE11=>"8/6/13 0:00",
:MMERGE12=>"Value", :MMERGE13=>nil, :MMERGE14=>"10/18/13 19:09", :MMERGE15=>"Value",
:FNAME=>"Value"}, {:EMAIL=>{:email=>"jason+7#marketingscience.co"}, :EMAIL_TYPE=>"html",
:MMERGE6=>"Value", :MMERGE7=>"Value", :MMERGE8=>nil, :MMERGE9=>nil, :MMERGE11=>"8/6/13
0:00", :MMERGE12=>"Value", :MMERGE13=>nil, :MMERGE14=>nil, :MMERGE15=>"Value",
:FNAME=>"Value"}, {:EMAIL=>{:email=>"jason+8#marketingscience.co"}, :EMAIL_TYPE=>"html",
:MMERGE6=>"Value", :MMERGE7=>"Value", :MMERGE8=>nil, :MMERGE9=>nil, :MMERGE11=>"8/7/13
0:00", :MMERGE12=>"Value", :MMERGE13=>nil, :MMERGE14=>nil, :MMERGE15=>"Value",
:FNAME=>"Value"}]
Here is the log output of result from the MailChimp call.
I, [2013-11-11T09:01:14.778691 #70827] INFO -- : {"add_count"=>3, "adds"=>
[{"email"=>"jason+3#marketingscience.co", "euid"=>"ab512177b4", "leid"=>"54637465"},
{"email"=>"jason+4#marketingscience.co", "euid"=>"eeb8388524", "leid"=>"54637469"},
{"email"=>"jason+5#marketingscience.co", "euid"=>"7dbc84cb75", "leid"=>"54637473"}],
"update_count"=>0, "updates"=>[], "error_count"=>0, "errors"=>[]}
Any advice on how to get all the fields to update in MailChimp is appreciated. Thanks.
Turns out the documentation for using the Gibbon gem to batch subscribe is not correct. You need to add the :merge_vars struct to contain the fields other than email and email type. My final code looks like the following. I'm also going to update this code in its entirety at: https://gist.github.com/analyticsPierce/7434085.
referrals.each_slice(3) do |batch|
begin
prepared_batch = batch.map do |referral|
{
:EMAIL => {:email => referral['email']},
:EMAIL_TYPE => 'html',
:merge_vars => {
:MMERGE6 => referral['field_1'],
:MMERGE7 => referral['field_2'],
:MMERGE8 => referral['field_3'],
:MMERGE9 => referral['field_4'],
:MMERGE11 => referral['field_5'],
:MMERGE12 => referral['field_6'],
:MMERGE13 => referral['field_7'],
:MMERGE14 => referral['field_8'],
:MMERGE15 => referral['field_9'],
:FNAME => referral['first_name']
}
}
end
#log.info("prepared_batch : #{prepared_batch}")
result = #gibbon.lists.batch_subscribe(
:id => #mc_list_id,
:batch => prepared_batch,
:double_optin => false,
:update_existing => true
)
#log.info("#{result}")
rescue Exception => e
#log.warn("Unable to load batch into mailchimp because #{e.message}")
end
end

Image not loading after updating a Google document

I have a problem trying to update a Google document containing an image. In the first revision, the image will load as expected. But after updating it with the same HTML code I keep getting a spinner instead of the image.
I am using the Ruby gem created by Google (https://github.com/google/google-api-ruby-client).
Here is my test code:
# Setting up the client instance
require "google/api_client"
require "tempfile"
client = Google::APIClient.new
client.authorization.client_id = "<CLIENTID>"
client.authorization.client_secret = "<CLIENTSECRET>"
client.authorization.redirect_uri = "<REDIRECTURI>"
client.authorization.scope = "https://www.googleapis.com/auth/drive"
client.authorization.access_token = "<ACCESSTOKEN>"
client.authorization.refresh_token = "<REFRESHTOKEN>"
drive = client.discovered_api("drive", "v2")
# Creating the document (IMAGE DISPLAYED CORRECTLY)
file = drive.files.insert.request_schema.new({"title" => "Test document", "mimeType" => "text/html"})
temp = Tempfile.new "temp.html"
temp.write "<h1>Testing!</h1><p>Lorem ipsum.</p><img width='400px' src='http://www.digitaleconomics.nl/wp-content/uploads/2013/04/see-how-your-google-results-measure-up-with-google-grader-video-6b8bbb4b41.jpg'>"
temp.rewind
media = Google::APIClient::UploadIO.new(temp, "text/html")
result = client.execute(:api_method => drive.files.insert, :body_object => file, :media => media, :parameters => {"uploadType" => "multipart", "convert" => true})
temp.close
# Updating the document (GETTING SPINNER INSTEAD OF IMAGE)
file = client.execute(:api_method => drive.files.get, :parameters => {"fileId" => result.data.to_hash["id"]}).data
file.title = "Updated test document"
temp = Tempfile.new "temp.html"
temp.write "<h1>Testing!</h1><p>Lorem ipsum.</p><img width='400px' src='http://www.digitaleconomics.nl/wp-content/uploads/2013/04/see-how-your-google-results-measure-up-with-google-grader-video-6b8bbb4b41.jpg'>"
temp.rewind
media = Google::APIClient::UploadIO.new(temp, "text/html")
result = client.execute(:api_method => drive.files.update, :body_object => file, :media => media, :parameters => {"uploadType" => "multipart", "convert" => true, "fileId" => result.data.to_hash["id"], "newRevision" => false})
temp.close
Also, setting newRevision to false does not prevent a new revision from being created.
Can anyone help me out?

How to use google-api-ruby-client with the Google Calendar API?

I've been reading the docs for the Google Calendar API and the google-api-ruby-client library, but I'm having a lot of trouble understanding them.
I have a Rails application that has a front end that lets users create objects called Events, and it saves them in a database on my server. What I would like is, after these Events are saved in the database, I want to call the Google Calendar API to create an event on a Google Calendar (that the server created, and only the server has access to modify that calendar).
I'm having lots of issues figuring out how to authenticate with the API using the ruby library. It doesn't make sense for me to use OAuth2 because I don't need to authorize anything with the user because I'm not interested in their data. I looked into Service Accounts (http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts), but it looks like Google Calendars is not supported by Service Accounts.
Anyone have any ideas? This is the code I was experimenting with (using Service Accounts):
#client = Google::APIClient.new(:key => 'my_api_key')
path_to_key_file = '/somepath/aaaaaa-privatekey.p12'
passphrase = 'my_pass_phrase'
key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase)
asserter = Google::APIClient::JWTAsserter.new(
'blah_blah#developer.gserviceaccount.com',
'https://www.googleapis.com/auth/calendar',
key)
# To request an access token, call authorize:
#client.authorization = asserter.authorize()
calendar = #client.discovered_api('calendar', 'v3')
event = {
'summary' => 'Appointment',
'location' => 'Somewhere',
'start' => {
'dateTime' => '2012-06-03T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2012-06-03T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'attendeeEmail'
},
#...
]
}
result = #client.execute!(:api_method => calendar.events.insert,
:parameters => {'calendarId' => 'primary'},
:body => JSON.dump(event),
:headers => {'Content-Type' => 'application/json'})
Then of course I get this error message: Google::APIClient::ClientError (The user must be signed up for Google Calendar.) because the Service Account does not support Google Calendars.
I think you'll still need a real google user to host the calendar instance. But once you've got the calendar created under your identity, you can share it with the service account. In the sharing settings for the calendar, just use the email address of the service account (my service account ends with #developer.gserviceaccount.com). With the right sharing permissions, your service account can create/alter the event info, and not mess with your specific identity. From there, you can share the calendar with more people (or public) for their consumption of the mirrored events.
The other hitch I've run into is that it seems you can only authorize() the service account once per expiration period. You'll have to save the token you get and reuse it for the next hour, and then fetch a new one.
I don't know anything about Ruby. But it seems like understanding the underlying REST queries would help debug your problem. I've documented them here: http://www.tqis.com/eloquency/googlecalendar.htm
I was having trouble with this too and finally got a handle on it. The bottom line is that Google Calendar API v3 requires OAuth and you need to setup an App/Project through the Google Developer Console and then request OAuth permission on the target Google account. Once authorization is granted, you'll want to save the refresh token and use it on subsequent calls to get new access tokens (which expire!). I wrote a detailed blog post about this here: http://www.geekytidbits.com/google-calendar-api-from-ruby/ and this is my example script that should hopefully help you understand the flow:
#gem install 'google-api-client'
require 'google/api_client'
#Setup auth client
client_secrets = Google::APIClient::ClientSecrets.load #client_secrets.json must be present in current directory!
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://www.googleapis.com/auth/calendar',
:access_type => "offline", #will make refresh_token available
:approval_prompt =>'force',
:redirect_uri => 'http://www.myauthorizedredirecturl.com'
)
refresh_token_available = File.exist?('refresh_token.txt')
if !refresh_token_available
#OAuth URL - this is the url that will prompt a Google Account owner to give access to this app.
puts "Navigate browser to: '#{auth_client.authorization_uri.to_s}' and copy/paste auth code after redirect."
#Once the authorization_uri (above) is followed and authorization is given, a redirect will be made
#to http://www.myauthorizedredirecturl.com (defined above) and include the auth code in the request url.
print "Auth code: "
auth_client.code = gets
else
#If authorization has already been given and refresh token saved previously, simply set the refresh code here.
auth_client.refresh_token = File.read('refresh_token.txt')
end
#Now, get our access token which is what we will need to work with the API.
auth_client.fetch_access_token!
if !refresh_token_available
#Save refresh_token for next time
#Note: auth_client.refresh_token is only available the first time after OAuth permission is granted.
#If you need it again, the Google Account owner would have deauthorize your app and you would have to request access again.
#Therefore, it is important that the refresh token is saved after authenticating the first time!
File.open('refresh_token.txt', 'w') { |file| file.write(auth_client.refresh_token) }
refresh_token_available = true
end
api_client = Google::APIClient.new
cal = api_client.discovered_api('calendar', 'v3')
#Get Event List
puts "Getting list of events..."
list = api_client.execute(:api_method => cal.events.list,
:authorization => auth_client,
:parameters => {
'maxResults' => 20,
'timeMin' => '2014-06-18T03:12:24-00:00',
'q' => 'Meeting',
'calendarId' => 'primary'})
puts "Fetched #{list.data.items.count} events..."
#Update Event
puts "Updating first event from list..."
update_event = list.data.items[0]
update_event.description = "Updated Description here"
result = api_client.execute(:api_method => cal.events.update,
:authorization => auth_client,
:parameters => { 'calendarId' => 'primary', 'eventId' => update_event.id},
:headers => {'Content-Type' => 'application/json'},
:body_object => update_event)
puts "Done with update."
#Add New Event
puts "Inserting new event..."
new_event = cal.events.insert.request_schema.new
new_event.start = { 'date' => '2015-01-01' } #All day event
new_event.end = { 'date' => '2015-01-01' }
new_event.description = "Description here"
new_event.summary = "Summary here"
result = api_client.execute(:api_method => cal.events.insert,
:authorization => auth_client,
:parameters => { 'calendarId' => 'primary'},
:headers => {'Content-Type' => 'application/json'},
:body_object => new_event)
puts "Done with insert."

Resources