Turn a partial into a json variable in the controller - json

Hi I need to turn the html of a partial into a json object (NOT TO BE RENDERED), but to be stored in a seperate format.
Something like this:
#json = (:partial => "/answers/likers" ,:type => :html)
Although the above obviously does not work, but hope you get the point, thanks!

Try render_to_string. It takes the same arguments as render, and just returns a string instead of outputting the data.
It looks like it's being deprecated but I can't find any new method that provides that same functionality for Rails 3. I tested it on a local Rails 3 setup, though, and it works for me. If anyone knows the "new" way to do this in Rails 3 please let me know, I'm interested now :)

Rails has a .to_json function. However, I never used this together with a partial ...

Related

Ruby on Rails: Best way to go trough a nested API JSON Response

I'm trying to get specific data from a bigger/nested API JSON Response. But because it's highly dynamic, it fails quite often because there are some branches missing down the JSON Tree.
Is there a good way or some best practices how to get the data?
Example:
#myrecords.cvss31 = jsonresponse["result"]["CVE_Items"][0]["impact"]["baseMetricV3"]["cvssV3"]["vectorString"]
In this case, sometimes it's throwing an error, because "cvssV3" is nil. Maybe in the future also "baseMetricV3" could be nil.
So, my approach would be to create 7 if-Statements - for every attribute. "if jsonresponse["result"].present?...", next: "if jsonresponse["result"]["CVE_Items"].present?" and so on. But that doesn't seem right.
I also tried something like "..["vectorString"].presence ||= "no NVD CVSS 3.1 Score"", but because the attribute before "vectorString" is missing, this doesn't seem to work either.
I also have a lot of other attributes to extract from that API. So basically I would have to write hundrets of conditional statements.
Is there a better way if I don't want to get ALL Data from that JSON Response extracted?
Putting it here for anyone stumbling on this issue. By using dig:
jsonresponse.dig("result", "CVE_Items", 0, "impact", "baseMetricV3", "cvssV3", "vectorString").presence || "no NVD CVSS 3.1 Score"

Accesing Json data after 'loading' it

With a lot of help from people in this site, I managed to get some Json data from an amazon page. The data, for example, looks like this.
https://jsoneditoronline.org/?id=9ea92643044f4ac88bcc3e76d98425fc
First I have a list of strings which is converted to a string.
script = response.xpath('//script/text()').extract()
#For example, I need the variationValues data
variationValues = re.findall(r'variationValues\" : ({.*?})', ' '.join(script))[0]
Then, in my code, I have this (not a great name, will be changed later)
variationValuesJson = json.loads(variationValues)
variationValuesJson is in fact a dictionary, so doing something like this
variationValues["size_name"][3]
Should return "5.5 M US"
My issue is that, when running the program, I get the string indices must be integers error. Anyone knows whats wrong?
Note: I have tried using 'size_name' instead of "size_name", same error
variationValues["size_name"][3] #this is the raw string which you have converted to variationValuesjson
I think this is not what you actually want.
Your code should be this.
variationValuesJson['size_name'][3] #use variationValuesjson ;)

Custom `returnFormat` in ColdFusion 10 or 11?

I've a function which is called from different components, .cfms or remotely. It returns the results of a query.
Sometimes the response from this function is manually inspected - a person may want to see the ID of a specific record so they can use it elsewhere.
The provided return formats, being wddx, json, plain all aren't very easily readable for a layman.
I'd love to be able to create a new return format: dump, where the result first writeDumped and then returned to the caller.
I know there'd be more complicated ways of solving this, like writing a function dump, and calling that like a proxy by providing the component, function and parameters so it can call that function and return the results.
However I don't think it's worth going that far. I figured it'd be great if I could just write a new return format, because that's just... intuitive and nice, and I may also be able to use that technique to solve different problems or improve various workflows.
Is there a way to create custom function returnFormats in ColdFusion 10 or 11?
(From comments)
AFAIK, you cannot add a custom returntype to a cffunction, but take a look at OnCFCRequest. Might be able to use it to build something more generic that responds differently whenever a custom URL parameter is passed, ie url.returnformat=yourType. Same net effect as dumping and/or manipulating the result manually, just a little more automated.
From the comments, the return type of the function is query. That being the case, there is simply no need for a custom return format. If you want to dump the query results, do so.
queryVar = objectName.nameOfFunction(arguments);
writeDump (queryVar);

Perl::Mechanize: running a simple crawler with a loop [multiple queries]

currently ironing out a way to parse the data of a page: http://www.foundationfinder.ch/
i love to do it in Perl: Well - i am just musing which is the best way to do the job.
Guess that i am in front of a nice learning curve. ;) This task will give me some nice Perl lessions. At the moment it goes abit over my head...;-)
So here is a sample-page:
... and as i thought i can find all 790 resultpages within a certain range between Id= 0 and Id= 100000 i thought, that i can go the way with a loop:
http://www.foundationfinder.ch/ShowDetails.php?Id=11233&InterfaceLanguage=&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=927&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=949&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=20011&InterfaceLanguage=1&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=10579&InterfaceLanguage=1&Type=Html
i thought i can go the Perl-Way but i am not very very sure: I was trying to use LWP::UserAgent on the same URLs [see below] with different query arguments, and i am wondering if LWP::UserAgent provides a way for us to loop through the query arguments? I am not sure that LWP::UserAgent has a method for us to do that. Well - i sometimes heard that it is easier to use Mechanize. But is it really easier!?
BTW; But if i am going the PHP way i could do it with Curl - couldnt i!?
Here is my approach: I tried to figure it out. And i digged deeper in the Manpages and Howtos. We can have a loop constructing the URLs and use Curl - repeatedly
As noted above: here we have some resultpages;
http://www.foundationfinder.ch/ShowDetails.php?Id=11233&InterfaceLanguage=&Type=Html
http://www.foundationfinder.ch/ShowDetails.php?Id=927&InterfaceLanguage=1&Type=Html
Alternatively we can add a request_prepare handler that computes and add the query
arguments before we send out the request.
Again: What is aimed: i want to parse the data and afterwards i want to store it in a local MySQL-database
should i define a extern_uid !?
and go like this:
for my $i (0..10000) {
$ua->get('http://www.foundationfinder.ch/ShowDetails.php?Id=', id => 21, extern_uid => $i);
# process reply
}
Well but now i get stuck- i need help - can i do the job like this!?
regards
zero
Dont do it like this. Use HTTP live headers (Firefox Plugin) or eqv. to see what the javasript does behind the scenes while you select what you need from here to get to that page (with the table).
To get the data from the table, use HTML::TableExtract or HTML::TreeBuilder::XPath if you want to use XPath
If you do want to iterate over the queries, just create another var:
my $a = 'http://www.foundationfinder.ch/ShowDetails.php?Id=' . $q . '&InterfaceLanguage=&Type=Html';
and increment $q as you go, make sure the page is valid before trying to load it with get

Serialize model into Query string

Would it be possible to serialize a model object into a query string?
I've no idea if this is even possible, but if not, what is the best way to do this?
<% Html.RenderAction("Grid", "Grid", new { gridModel= ViewData["model"]}); %>
The Model is containing ca 20 properties, and creating the querystring with them in individually would make it a pain to work with and it would look really ugly. so what alternatives do I have?
To answer directly, you could use something like JSON.NET to serialize it to ASCII and then base64 encode it.
However, there are very real limits on how much data you can include in the query string and I'd hesitate to do this.
The closest thing I can think of would be to create a GUID, use that GUID as a key to store the object in Session, then pass the RenderAction the GUID. That action would pull the object out of the Session and then remove it from the Session.
Quick pseudocode (not guaranteed to even compile, much less work)
var _requestKey = Guid.NewGuid();
Session[requestKey] = gridModel;
Then on the other side:
var gridModel = Session[requestKey] as GridModelType;
Session[requestKey] = null;
I ended up using Form for this. Wasn't as pretty and nice as I wanted, but as far as I understand the only good way I could do it.