Reputation: 51
Need to submit an HTTP POST request of a json string. Have all of the RESTful parts working, and verified correctly. This works if I hard code the elements inside the array. I am wanting to loop through one of the arrays in the JSON string, the "Attachments Array".
The loop would look something like:
@days = Daily.all
@days[0..11] do |dailys|
#loop that builds json to post
end
#RESTful HTTP POST request
The only problem is, I don't know how to implement a loop inside of a JSON string for only one array.
My code so far for testing out the HTTP POST
#!/usr/bin/ruby
require 'net/http'
require 'uri'
require 'json'
require 'jbuilder'
uri = URI.parse("<POST URL>")
header = {'Content-Type' => 'text/json'}
payload = {
channel: "<channel>",
username: "<username>",
# Wish to loop through the "Attachments" Array
attachments: [
{
param: "Text",
text: "Text",
pretext: "Optional Text",
color: 'good',
fields: [
{
Title: "Title field",
value: "First Value",
short: false
},
{
title: "Field Title",
value: "Field Value",
short: true
},
{
title: "Second Field Title",
value: "Second Field Value",
short: true
}
]
}
]
}
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Post.new(uri.request_uri, header)
req.body = payload.to_json
resp = http.request(req)
puts resp
Upvotes: 1
Views: 867
Reputation: 32933
Your code is looping through a bunch of Daily objects (though you're calling each one 'dailys' inside the loop which is confusing). You don't really explain what you want to do, but if you wanted to make a json object using some of the attributes of the Daily objects you have, you could do it like this.
hash = Daily.find(:all, :limit => 12).map{|daily| {:foo => daily.bar, :chunky => daily.chicken}}.to_json
If you give some details of the json string you want to make from your daily objects then i could give you some less silly code, but the approach is correct: build a ruby data structure then convert it to json with to_json
EDIT: following on from your comment, i would do this.
hash = Daily.find(:all, :limit => 12, :order => "id desc").map{|daily| {param: daily.title, fields: [{title: "Task Completed?", value: daily.completed, short: true}]} }
json = hash.to_json
Couple of notes:
1) Daily
is a class, not an object (while classes are also objects in Ruby, i think that in rails it's better to refer to it as the class.
2) By the last 12 elements
i assume you mean the most recently saved records: this is what the :order option is for.
Upvotes: 3