Migrating from Mandrill to SparkPost -- Rails API - ruby-on-rails

I am migrating from Mandrill to SparkPost and have a Rails back-end.
The data structure I currently have is the following --
message = {
subject: "Welcome",
merge_vars: [{
rcpt: user.email,
vars: email_vars(user)
}],
to:[{
email: user.email,
name: user.name
}],
track_clicks: true,
track_opens: true,
inline_css: true,
}
This sends the response --
m = Mandrill::API.new
template_content = []
result = m.messages.send_template 'email-confirmation', template_content, message
Would I need to update the JSON data structure at all?
Once JSON is good, how do I pass values to specific template with SparkPost?
I attempted the following --
m = SparkPost::Client.new()
template_content = []
result = m.messages.send_template 'email-confirmation', template_content, message
But I have also seen this --
host = 'https://api.sparkpost.com'
SparkPost::Request.request("#{host}/api/v1/transmissions", API_KEY, {
recipients: [
{
address: { email: user.email },
substitution_data: {
first_name: user.name,
email: user.email
}
}
],
content: {
template_id: 'email-confirmation'
},
substitution_data: {
name: user.name,
email: user.email
}
})
Appreciate the help!

If you're using the official gem, it has a convenient method called send_payload which you can use to send a prepared payload.
The substitution_data inside recipients collection is a per recipient substitution.
For example, I've following templates.
To send using this template, this is my complete code
sp = SparkPost::Client.new() # pass api key or get api key from ENV
payload = {
recipients: [
{
address: { email: 'RECIPIENT1' },
substitution_data: {
name: 'User one',
username: 'userone'
}
}, {
address: { email: 'RECIPIENT2' },
substitution_data: {
name: 'User two',
username: 'user2'
}
}
],
content: {
template_id: 'test-template'
},
substitution_data: {
company: 'Awesome company'
}
}
response = sp.transmission.send_payload(payload)
p response
The email will look like
Hello User one, Your username, userone, is created. Thanks Awesome company

Related

Iterate over hash and return newly formed hash

I'm trying to iterate over hash and return new hash. My original hash is:
companies = {
company_id: {
"0": { title: "Google", address: "New str" },
"1": { title: "Facebook", address: "Old str." },
"2": { title: "Amazon", address: "River str." }
}
}
I want to return hash that is structured this way:
{
title: "Google",
address: "New str."
}
If company_id equal to "0" I would need to return details of that company, similar to below:
companies.each do |k,v|
v.each do |k,v|
if k.to_s == "0"
title: v[:title]
address: v[:address]
end
end
end
Iteration above doesn't return me hash, how can I get structured hash that I need? Thanks.
Simply do
companies[:company_id][:"0"]
# { title: "Google", address: "New str." }

STRIPE NameError: undefined local variable or method `request' for main:Object

I am trying to update a connected account so it can accept the terms of service and be able to create a payout. however, when I try to run the code in the console so it updates it doesn't update and that error regarding the ip address pops up. I am following stripe's documentation to update accounts.
I have tried not including ip into the tos_acceptance, but the ip is neccessary!
I tried 'ip' and putting quotes around request.remote_ip
"acct_id_12345", {
tos_acceptance: {
date: Time.now.to_i,
ip: request.remote_ip,
},
},
)
the error that appears is:
NameError: undefined local variable or method `request' for main:Object
You're running the code somewhere where the request method does not exist, eg. outside of a controller.
I just needed to name the request variable this is the final product:
account = Stripe::Account.create({
country: "US",
type: "custom",
requested_capabilities: ["transfers", "card_payments"],
email: current_user.email,
business_type: "company",
company: {
name: business.name,
address: {
city: business.city,
country: 'US',
line1: business.address,
postal_code: business.zip_code,
state: business.state,
},
phone: '3128880912',
tax_id: '000000000',
},
external_account: {
country: "US",
object: "bank_account",
account_number: params[:account_number],
routing_number: params[:routing_number],
},
settings: {
payouts: {
schedule: {
interval: 'monthly',
monthly_anchor: 1,
},
},
},
business_profile: {
url: business.website,
mcc: 5734,
},
tos_acceptance: {
date: Time.now.to_i,
ip: '181.48.147.209',
},
})

How to fix "Unexpected end of JSON"

I had my users page displaying users but then when I stopped working on the code for a while and came back to it I am getting an error which says
Error while processing route: users Unexpected end of JSON input SyntaxError: Unexpected end of JSON input
and also
Uncaught SyntaxError: Unexpected end of JSON input
I don't know where to start on trying to fix this issue.
Here is the front-end code in the route file users.js:
model() {
return this.get("store").findAll("user");
},
Here is the api code in the users controller:
# GET /users
def index
render jsonapi: User.all
end
When I go to http://localhost:3000/users I get the following json:
{
data: [
{
id: "1",
type: "users",
attributes: {
name: "Katie",
email: "katie#gmail.com"
}
},
{
id: "2",
type: "users",
attributes: {
name: "Katie",
email: "katie#gmail.com"
}
},
{
id: "3",
type: "users",
attributes: {
name: "Katie",
email: "katie#gmail.com"
}
},
{
id: "4",
type: "users",
attributes: {
name: "K",
email: "k"
}
},
{
id: "5",
type: "users",
attributes: {
name: "R",
email: "r"
}
}
],
jsonapi: {
version: "1.0"
}
}
I also get this warning: WARNING: The server returned an empty string for GET http://localhost:3000/users, which cannot be parsed into a valid JSON. Return either null or {}.
/users route is not providing the valid JSON output is the reason for this error. You can check /users output using POSTMAN or writing the below code,
let url ="/users";
Ember.$.getJSON(url).then((result) => {
console.log(' Result ', result);
});

How to convert Json in Ruby on Rails?

I'm creating an API with Rails and Neo4j and i have a query looks like this on my model
Neo4j::Session.query.match('(User)').where("lower(User.first_name) =~ '.*#{params[:name].downcase}.*'").return('User')
this query return json looks like
[
{
User: {
user: {
username: null,
password: null,
first_name: "ayman",
last_name: "eldeeb",
email: "ayman#gmail.com",
phone: "44555",
avatar: "url",
birthdate: "1990-12-26"
}
}
}
]
Now, how to convert this json in Ruby on Rails to this below?
{
users: [
{
id: 0,
username: null,
first_name: "adham",
last_name: "eldeeb",
phone: "010220234",
email: null,
avatar: "url",
birthdate: null
}
]
}
Not sure, but this can probably work..
require 'json' #this has to be in the top
.....
#data = JSON.parse(Neo4j::Session.query.match('(User)').where("lower(User.first_name) =~ '.*#{params[:name].downcase}.*'").return('User'))
Now #data will be a ruby variable parsed from the JSON output..
Now to get your desired output, maybe the following snippet can help
#desired_data = []
#data.each do |d|
#desired_data << d[:User][:user] # this could be d["User"]["user"] if this dosen't work
end

Iterate through properties of current context objects in Dust.js

Given the JSON object:
errors =
{
hashed_password: {
message: 'Validator "Password cannot be blank" failed for path hashed_password',
name: 'ValidatorError',
path: 'hashed_password',
type: 'Password cannot be blank' },
username: {
message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank' },
email: {
message: 'Validator "Email cannot be blank" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email cannot be blank' },
name: {
message: 'Validator "Name cannot be blank" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'Name cannot be blank' }
}
How do I iterate through the properties of each "current context" object?
I would think you do something like this:
{#errors}
{#.}
{type}
{/.}
{/errors}
If you really have to put meaningful data into object keys, consider writing a contextual helper, as per:
https://github.com/akdubya/dustjs/issues/9
Dust.js output JSON key
It is not possible to iterate through members of an object in Dust. Part of the reason is that you cannot know the order of the members. Another part is that this is seen as bringing too much logic into Dust.
Instead, you can change the JSON to look more like this:
{
errors: [
{
hashed_password: {
message: 'Validator "Password cannot be blank" failed for path hashed_password',
name: 'ValidatorError',
path: 'hashed_password',
type: 'Password cannot be blank'
}
},
{
username: {
message: 'Validator "Username cannot be blank" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'Username cannot be blank'
}
},
{
email: {
message: 'Validator "Email cannot be blank" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email cannot be blank'
}
},
{
name: {
message: 'Validator "Name cannot be blank" failed for path name',
name: 'ValidatorError',
path: 'name',
type: 'Name cannot be blank'
}
]
}
You can iterate over an object using a helper.
For example, you could define a helper like this one:
dust.helpers.iter = function(chunk, context, bodies, params) {
var obj = dust.helpers.tap(params.obj, chunk, context);
var iterable = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = obj[key];
iterable.push({
'$key': key,
'$value': value,
'$type': typeof value
});
}
}
return chunk.section(iterable, context, bodies);
};
Then, in your template, you would loop through like this:
{#iter obj=errors}
{$value.type}
{/iter}

Resources