Inject JS variable into a haml template - ruby

I'm trying use HTML5 localStorage with a Ruby haml template and need to be able to get the value of localStorage.getItem('myItem') to pass to a java applet (code stripped down):
- content_box("MyBox") do
%object{:classid => "clsid:xxx"}
%param{:name => "myItem", :value => "javascript:localStorage.getItem('myItem')"}
%comment
%EMBED{:myItem => "javascript:localStorage.getItem('myItem')"}
%noembed
Is there a good way to do this? I can do something like:
:javascript
document.write("<param name='myItem' value="+localStorage.getItem('myItem')+">"
but that's so ugly!
Note that this is an object I'm embedding, and need the value to be present before document_ready; I cannot select the object and append the value to it on document_ready. The only other way I can think of is to do an ajax submission to make the value a Ruby variable ahead of time, but that's really unnecessary.
Thanks!

Sometimes the only way that works is ugly.
IF your data is stored on the client, creating a server request/page/action just to get the data and pass it back in a different form straight back to the client is uncessessary, and arguably uglier.
Go with using javascript to add the <param> tag.

If the object depends on JavaScript anyway, you may as well just write the whole element with JavaScript instead of just the param. Then you can do it on document ready.

Related

Best way to output the content i load from ajax

I want to load objects with ajax and then for every object make with options.
What is better to do when i load content from server via ajax:
put everything in a string variable (including html tags) named output with += and put it on a loop for each object,then append it.
append an output for every object i load in a div
or a better solution
if there is a better solution is there anyone who can help me ?
Well that really depends on a technology stack that you are using.
But in essence it is exactly what is going on.
You have some array of products coming back from an ajax request.
You want to clear out the contents of the area where you are inserting those.
Then you wanna iterate over your collection of items and using some kind of template generate an html for each one. the simplest one in plain java script would be string concatenation.
then you concatenate them all and insert the result as innerHTML inside your container.
It may be ugly for a start but as you will learn more - you will improve.

Use '#' with method in codeigniter like www.mydomain.com/controller#method

Is it possible to call a method of any controller like this:
www.mydomain.com/controller#method
instead of
www.mydomain.com/controller/method
#method(hash) values not detected by PHP, even with $_SERVER["REQUEST_URI"],
So It's not possible. You can detect the hash value with javascript alert(window.location.hash); OR Use ajax to prevent page refresh.

Obtain XML element's value from REST server response using Ruby

n00b REST question. I'm making a GET request to an API's endpoint and getting the proper XML response. The question I have is, how do I get the value of a particular XML element in the servers REST response using Ruby?
So let's say one of the elements is 'Body' and I want to assign its value 'Blah blah blah' to a variable
Part of the XML response:
<Body>Blah blah blah</Body>
How would I do that with the response? Basically I want to do something like this
variable = params["Body"]
Thanks in advance!
The best solution is to use RestClient or HTTParty and have it parse the response for you.
Otherwise, you'll have to parse the response itself using a library such as Nokogiri:
doc = Nokogiri.XML(response)
variable = doc.at("body").text
You'll want to use an XML parser of some kind.
It sounds like you want something like XmlSimple, which will turn an XML document into ruby arrays and hashes. There's tons of examples of how to use it on the page that has been linked.
One thing to be aware of is that XML to native container mappings are imperfect. If you're dealing with a complex document, you'll likely want to use a more robust parser, like Nokogiri.
If you want full XML Object Mapping, HappyMapper is a decent library, although it isn't very active anymore. It can work with XML from any source, so you'll still want something like the libraries mentioned by #Fitzsimmons or #MarkThomas to do the HTTP request.

Parse JSON from Jenkins, once hash, then nil

Jenkins gives me JSON from http://jenkins.net/jobs/MyJob/lastBuild/api/json
Then I use HTTParty to get it like so:
response = self.get( url, options )
change = response['changeSet']['items'][0]
This gives me the content of the last changes. change.class returns "Hash".
If I try this:
change = response['changeSet']['items'][0]['revision']
as looking at the JSON suggests, I get "Undefined method '[]' on NilObject".
What am I doing wrong?
EDIT3:
Of course, the problem lies between User and keyboard. The method was first called on another JSON, because it's polling the changes for more than one project, and one of the returned JSON objects didn't contain those keys. D'oh!
Sorry.
If you get that kind of error you're hitting an empty key and then trying to use it as if it's populated. Without seeing what your JSON is, it's hard to say, but one of those is failing. You'll want to inspect these:
response['changeSet']
response['changeSet']['items']
response['changeSet']['items'][0]
If any of those end up being nil then you can pin-point the problem. JSON comes back as an arbitrary structure so chaining a bunch of calls together without any sort of testing can lead to trouble.

How can I get Mechanize objects from Mechanize::Page's search method?

I'm trying to scrape a site where I can only rely on classes and element hierarchy to find the right nodes. But using Mechanize::Page#search returns Nokogiri::XML::Elements which I can't use to fill and submit forms etc.
I'd really like to use pure CSS selectors but matching for classes seems to be pretty straight forward with the various _with methods too. However, matching things like :not(.class) is pretty verbose compared to simply using CSS selectors while I have no idea how to match for element hierarchy.
Is there a way to convert Nokogiri elements back to Mechanize objects or even better get them straight from the search method?
Like stated in this answer you can simply construct a new Mechanize::Form object using your Nokogiri::XML::Element retrieved via Mechanize::Page#search or Mechanize::Page#at:
a = Mechanize.new
page = a.get 'https://stackoverflow.com/'
# Get the search form via ID as a Nokogiri::XML::Element
form = page.at '#search'
# Convert it back to a Mechanize::Form object
form = Mechanize::Form.new form, a, page
# Use it!
form.q = 'Foobar'
result = form.submit
Note: You have to provide the Mechanize object and the Mechanize::Page object to the constructor to be able to submit the form. Otherwise it would just be a Mechanize::Form object without context.
There seems to be no central utility function to convert Nokogiri::XML::Elements to Mechanize elements but rather the conversions are implemented where they are needed. Consequently, writing a method that searches the document by CSS or XPath and returns Mechanize elements if applicable would require a pretty big switch-case on the node type. Not exactly what I imagined.

Resources