cucumber , jQuery and redirects - ruby-on-rails

I have a select tag on my page, I have made via jQuery on domready a listener for the change event. In this listener I redirect the user to the same page with a parameter in the url.
When I test the functionality manual, it works very well.
When I run the test, it fails, the redirect doesn't work.
How I can make it work ?
#javascript
Scenario:
When I select "2010" from "year_select"
And I wait 5 seconds
Then "2010" should be selected for "year_select"
Then I should see "time_sheet?year=2010" with html
The test fails, I see time_sheet?year=2011 (the default value) in my html source, manual I see the correct value. It is not updated via Javascript, but according to te year variable passed in the url (after the redirect)
My jQuery code:
jQuery(document).ready(function(){
var yearSelect = jQuery("#year_select");
yearSelect.change(function(){
window.location = "/time_sheet_admin?year="+yearSelect.val();
});
});
What I make wrong ?

I think u have missed out _admin in the scenario. Use time_sheet_admin instead of time_sheet in the scenario. If my suggestions is useless sorry for that.

What I usually do for testing complex JS stuff is to put them in a function and then test if that function was called:
selectChanged = function() {
window.location = "/time_sheet_admin?year="+jQuery("#year_select").val();
}
*note no need for the variable assignment because you only called it once.
then in your feature:
Then I should see "time_sheet?year=2010" in the url
step definition:
When /Then I should see "time_sheet?year=2010" in the url/ do |seconds|
page.execute_script("selectChanged()")
end

Related

NetSuite/Suitescript/Workflow: How do I open a URL from a field after clicking button?

I have a workflow that adds a button "Open Link" and a field on the record called "URL" that contains a hyperlink to an attachment in NetSuite. I want to add a workflow action script that opens this url in a different page. I have added the script and the workflow action to the workflow. My script:
function openURL() {
var url = nlapiGetFieldValue('custbody_url');
window.open(url);
}
I get this script error after clicking the button: "TypeError: Cannot find function open in object [object Object].
How can I change my script so it opens the URL in the field?
(This function works when I try it in the console)
Thanks!
Do you want it to work when the record is being viewed or edited? They have slightly different scripts. I'm going to assume you want the button to work when the record is being viewed, but I'll write it so it works even when the document is being edited as well.
The hard part about the way Netsuite has set it up is that it requires two scripts, a user event script, and a client script. The way #michoel suggests may work too... I've never inserted the script by text before personally though.
I'll try that sometime today perhaps.
Here's a user event you could use (haven't tested it myself though, so you should run it through a test before deploying it to everyone).
function userEvent_beforeLoad(type, form, request)
{
/*
Add the specified client script to the document that is being shown
It looks it up by id, so you'll want to make sure the id is correct
*/
form.setScript("customscript_my_client_script");
/*
Add a button to the page which calls the openURL() method from a client script
*/
form.addButton("custpage_open_url", "Open URL", "openURL()");
}
Use this as the Suitescript file for a User Event script. Set the Before Load function in the Script Page to userEvent_beforeLoad. Make sure to deploy it to the record you want it to run on.
Here's the client script to go with it.
function openURL()
{
/*
nlapiGetFieldValue() gets the url client side in a changeable field, which nlapiLookupField (which looks it up server side) can't do
if your url is hidden/unchanging or you only care about view mode, you can just get rid of the below and use nlapiLookupField() instead
*/
var url = nlapiGetFieldValue('custbody_url');
/*
nlapiGetFieldValue() doesn't work in view mode (it returns null), so we need to use nlapiLookupField() instead
if you only care about edit mode, you don't need to use nlapiLookupField so you can ignore this
*/
if(url == null)
{
var myType = nlapiGetRecordType();
var myId = nlapiGetRecordId();
url = nlapiLookupField(myType, myId,'custbody_url');
}
//opening up the url
window.open(url);
}
Add it as a Client Script, but don't make any deployments (the User Event Script will attach it to the form for you). Make sure this script has the id customscript_my_client_script (or whatever script id you used in the user event script in form.setScript()) or else this won't work.
Another thing to keep in mind is that each record can only have one script appended to it using form.setScript() (I think?) so you may want to title the user event script and client script something related to the form you are deploying it on. Using form.setScript is equivalent to setting the script value when you are in the Customize Form menu.
If you can get #michoel's answer working, that may end up being better because you're keeping the logic all in one script which (from my point of view) makes it easier to manage your Suitescripts.
The problem you are running into is that Workflow Action Scripts execute on the server side, so you are not able to perform client side actions like opening up a new tab. I would suggest using a User Event Script which can "inject" client code into the button onclick function.
function beforeLoad(type, form) {
var script = "window.open(nlapiGetFieldValue('custbody_url'))";
form.addButton('custpage_custom_button', 'Open URL', script);
}

Caching visited page in Jquery Mobile

I work on Jquery Mobile/Phonegap app for android.
I´d like my app to "remember" that(if) the user has visited one of my pages. For example if he once visits "page1.html", this action should be cached in the phone memory, so that when the user opens the app again there should be possibility to navigate to this "page2.html" directly from "index.thml".
Please, if you have a code suggestion, tell me also how/where do I use it, because sometimes for starters like me it is realy hard to understand what to do with a little piece code.
Thank you very much!
You can use HTML5 local storage for this purpose.
Each time when a page is shown you can save/update the current page URL to a local storage variable, say 'lastVisit', as below:
$(document).on('pageshow', function (event, data) {
var currentPage = $('.ui-page-active').data('url');
localStorage.setItem("lastVisit", currentPage);
});
If you are not getting $('.ui-page-active').data('url'), then you can use $.mobile.activePage.attr('id') which will give you the current page id.
So next time, when the user opens the app again, you can check whether this local storage variable is set and can action accordingly.
The code will look like as below:
$(document).on('mobileinit', function(){
var lastVisit = '';
if(localStorage.getItem("lastVisit") != null){
lastVisit = localStorage.getItem("lastVisit");
}
if(lastVisit){
document.location.href = lastVisit;
}
});
You can use these codes in the header section scripts.

Rendering dynamic scss-files with ajax, rails

As the title suggests, my main objective is to render a dynamic scss(.erb) file after an ajax call.
assets/javascripts/header.js
// onChange of a checkbox, a database boolean field should be toggled via AJAX
$( document ).ready(function() {
$('input[class=collection_cb]').change(function() {
// get the id of the item
var collection_id = $(this).parent().attr("data-collection-id");
// show a loading animation
$("#coll-loading").removeClass("vhidden");
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// removal of loading animation, a bit delayed, as it would be too fast otherwise
setTimeout(function() {
$("#coll_loading").addClass("vhidden");
}, 300);
},
});
});
});
controller/collections_controller.rb
def toggle
# safety measure to check if the user changes his collection
if current_user.id == Collection.find(params[:id]).user_id
collection = Collection.find(params[:id])
# toggle the collection
collection.toggle! :auto_add_item
else
# redirect the user to error page, alert page
end
render :nothing => true
end
All worked very smooth when I solely toggled the database object.
Now I wanted to add some extra spices and change the CSS of my 50+ li's accordingly to the currently selected collections of the user.
My desired CSS looks like this, it checks li elements if they belong to the collections and give them a border color if so.
ul#list > li[data-collections~='8'][data-collections~='2']
{
border-color: #ff2900;
}
I added this to my controller to generate the []-conditions:
def toggle
# .
# .
# toggle function
# return the currently selected collection ids in the [data-collections]-format
#active_collections = ""
c_ids = current_user.collections.where(:auto_add_item => true).pluck('collections.id')
if c_ids.size != 0
c_ids.each { |id| #active_collections += "[data-collections~='#{id}']" }
end
# this is what gets retrieved
# #active_collections => [data-collections~='8'][data-collections~='2']
end
now I need a way to put those brackets in a scss file that gets generated dynamically.
I tried adding:
respond_to do |format|
format.css
end
to my controller, having the file views/collections/toggle.css.erb
ul#list<%= raw active_collections %> > li<%= raw active_collections %> {
border-color: #ff2900;
}
It didn't work, another way was rendering the css file from my controller, and then passing it to a view as described by Manuel Meurer
Did I mess up with the file names? Like using css instead of scss? Do you have any ideas how I should proceed?
Thanks for your help!
Why dynamic CSS? - reasoning
I know that this should normally happen by adding classes via JavaScript. My reasoning to why I need a dynamic css is that when the user decides to change the selected collections, he does this very concentrated. Something like 4 calls in 3 seconds, then a 5 minutes pause, then 5 calls in 4 seconds. The JavaScript would simply take too long to loop through the 50+ li's after every call.
UPDATE
As it turns out, JavaScript was very fast at handling my "long" list... Thanks y'all for pointing out the errors in my thinking!
In my opinion, the problem you've got isn't to do with CSS; it's to do with how your system works
CSS is loaded static (from the http request), which means when the page is rendered, it will not update if you change the CSS files on the server
JS is client side and is designed to interact with rendered HTML elements (through the DOM). This means that JS by its nature is dynamic, and is why we can use it with technologies like Ajax to change parts of the page
Here's where I think your problem comes in...
Your JS call is not reloading the page, which means the CSS stays static. There is currently no way to reload the CSS and have them render without refreshing (sending an HTTP request). This means that any updating you do with JS will have to include per-loaded CSS
As per the comments to your OP, you should really look at updating the classes of your list elements. If you use something like this it should work instantaneously:
$('li').addClass('new');
Hope this helps?
If I understood your feature correctly, actually all you need can be realized by JavaScript simply, no need for any hack.
Let me organize your feature at first
Given an user visiting the page
When he checks a checkbox
He will see a loading sign which implies this is an interaction with server
When the loading sign stopped
He will see the row(or 'li") he checked has a border which implies his action has been accepted by server
Then comes the solution. For readability I will simplify your loading sign code into named functions instead of real code.
$(document).ready(function() {
$('input[class=collection_cb]').change(function() {
// Use a variable to store parent of current scope for using later
var $parent = $(this).parent();
// get the id of the item
var collection_id = $parent.attr("data-collection-id");
show_loading_sign();
// AJAX call
$.ajax({
type : 'PUT',
url : "/collections/" + collection_id + "/toggle",
success : function() {
// This is the effect you need.
$parent.addClass('green_color_border');
},
error: function() {
$parent.addClass('red_color_border');
},
complete: function() {
close_loading_sign(); /*Close the sign no matter success or error*/
}
});
});
});
Let me know if my understanding of feature is correct and if this could solve the problem.
What if, when the user toggles a collection selection, you use jquery change one class on the ul and then define static styles based on that?
For example, your original markup might be:
ul#list.no_selection
li.collection8.collection2
li.collection1
And your css would have, statically:
ul.collection1 li.collection1,
ul.collection2 li.collection2,
...
ul.collection8 li.collection8 {
border-color: #ff2900;
}
So by default, there wouldn't be a border. But if the user selects collection 8, your jquery would do:
$('ul#list').addClass('collection8')
and voila, border around the li that's in collection8-- without looping over all the lis in javascript and without loading a stylesheet dynamically.
What do you think, would this work in your case?

Chosen not working in jquery dialog on reloading mvc partial

I am loading two MVC Partial Views in jQuery UI dialog using following code for editing and adding a record:
$.get(url, function(data)
{
dialogDiv.html(data);
var $form = $(formid);
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
var dat = $form.data("unobtrusiveValidation");
var opts = dat ? dat.options || '' : '';
$form.validate(opts);
//THIS FUNCTION ADDS PLUGINS ETC.
runEditCreateStartScripts();
dialogDiv.dialog('open');
});
Following is the function that wires-up chosen functionality.
function runEditCreateStartScripts(){
$("select.chzn-select").chosen(
{
no_results_text: "no match",
allow_single_deselect: true
});
}
Everything is perfect on first call. After opening one dialog say edit a few times everything is broken. There is only hyperlink available in place of chosen stuff. This also happens if I open one dialog say add and then second dialog. The bindings and other functionality from first one (add) is gone.
Any insights on why this might be happening?
The problem that caused my issue was that the modals I was loading via AJAX had inputs with the SAME ID as an input field that was already on the page (using Django that has generic ID generators for model fields). This caused collision between the two inputs when re-triggering .chosen() on the selector. When I made the ID fields unique, all worked as expected.
Hope this would have helped.

mobile.changepage requiring page refresh

I'm using $.mobile.ChangePage() to navigate from one HTML page to another. But the contents of the page is not changing. while doing so the page URL changes but the new page is not loaded. it requires to be refreshed to load.
you should use JavaScript function to change the page..using
window.location = 'your page ';
hope it will resolve your problem !
In the code that you provided in the comments above, you are likely getting an error stating that next_page is not defined. Given that you are dealing with jQuery Mobile, try assigning the click handler slightly differently:
Change the definition of the link to something like this:
<a id="btnNextPage" href="#" >Details</a>
You don't have to give it an id - you could just use selectors to identify the link in the following javascript:
// the event handler
function next_page() {
$.mobile.changePage("http://www.google.com", {transition:"slide"});
}
// assign the click event when the DOM is ready
$(function() {
$("#btnNextPage").click ( next_page );
});

Resources