invoking a JavaScript function from a Ruby on Rails controller

I need to implement a function that is currently written in JavaScript into my Ruby on Rails controller (.rb). This function dynamically generates and fills a select element with optgroup options.

How can I convert this functionality into Ruby code? I'm specifically looking for alternatives to JavaScript methods like

document.createElement("optgroup");

Below is the original JavaScript code:


enter function nbFct() {
var clipLists = ["Default", "Recent", "Sticky lists"];
var option1 = ["a", "b"];
var option2 = ["a", "x", "c"];
var option3 = ["f", "e", "c", "d"];
var listType = [];
var optionType = [];
for (var i = 0; i < clipLists.length; i++) {
// create dynamic optgroup from clipLists
listType[i] = document.createElement("optgroup");
listType[i].label = clipLists[i];   
//  alert(listType[i].label);
if(listType[i].label ==  "Default"){
    for (var j = 0; j < option3.length; j++) {
// create options and attach to optgroups
    optionType[j] = document.createElement("option");
    optionType[j].value = option3[j];
//      alert(optionType[j].value) ;
    optionType[j].appendChild(document.createTextNode(option3[j]));
    listType[i].appendChild(optionType[j]); 
    }
}
else if(listType[i].label ==  "Recent"){
    for (var j = 0; j < option2.length; j++) {
// create options and attach to optgroups
    optionType[j] = document.createElement("option");
    optionType[j].value = option2[j];
//      alert(optionType[j].value) ;
    optionType[j].appendChild(document.createTextNode(option2[j]));
    listType[i].appendChild(optionType[j]); 
    }
   }
   else{
      for (var j = 0; j < option1.length; j++) {
  // create options and attach to optgroups
        optionType[j] = document.createElement("option");
        optionType[j].value = option1[j];
  //            alert(optionType[j].value) ;
        optionType[j].appendChild(document.createTextNode(option1[j]));
        listType[i].appendChild(optionType[j]); 
      }
    }
  }
 // set the default
 optionType[1].selected = true;
 // clear select menu and append optgroups
 var selectMenu = document.getElementById("clipListOption");
while (selectMenu.hasChildNodes()) {
selectMenu.removeChild(selectMenu.firstChild);
}
 for (var i = 0; i < clipLists.length; i++) {
    if (listType[i].hasChildNodes()) { selectMenu.appendChild(listType[i]); }
  }
} 

Answer №1

Performing this task isn't straightforward, except through convoluted methods of hacking. In a Rails framework, the controller is unable to access the inner workings of the view. Even if it could, extracting JavaScript and executing it in its own local environment would be challenging. Additionally, such actions would go against the principles of the MVC architecture.

If necessary, achieving this goal might entail:

  • Sending the JS function string via a client-side POST request.

  • Evaluating and parsing the JS code.

  • Converting the JS into a Ruby string.

  • Evaluating the Ruby string within the controller's specific context.

This process is quite extensive. Ideally, the model should handle most of the heavy lifting, with the controller providing guidance and passing the results to the view.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enzyme in Action: Using React.js to Emulate a Click Event

I have been working on a React.js application which is a straightforward Cart app. You can take a look at the code sandbox here: https://codesandbox.io/s/znvk4p70xl The issue I'm facing is with unit testing the state of the application using Jest and ...

Implementing multiple content changes in a span using javascript

Having an issue with a pause button where the icon should change on click between play and pause icons. Initially, the first click successfully changes the icon from a play arrow to a pause icon, but it only changes once. It seems like the else part of the ...

The continuous looping issue is being triggered when implementing a like button using firestore along with useEffect and UseState

I have developed a component to be loaded into various cards for displaying data. This particular component retrieves and stores data from the card (sale_id) onto the database. import { LikeButtonStyle } from './LikeButton.styled'; import { Image ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Using jQuery and Ajax to submit a form in Rails applications

Solved the previous issue, now moving on to another related question. Below is the JavaScript code I am working with: jQuery.ajaxSetup({ 'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") } }) jQuer ...

Using an HttpInterceptor in Angular 1.5 for managing timeouts

Hello everyone, I have been attempting to implement a global httpInterceptor that will display a custom popup message when a client timeout occurs, rather than a server timeout. I came across a helpful article on this topic: Angular $http : setting a prom ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

Incorporating dynamic data binding using AngularJS in a span tag

In my view, I am using this Angular expression: <span ng-if="{{list.StoreList ? (list.StoreList.length ' Products)' : '(0 Products)'}}"> </span> The purpose is to display the count of items in StoreList if there are any, ...

Error encountered while running npm build command for HTML Webpack Plugin

As a newcomer to webpack, I'm currently attempting to integrate it into a project that utilizes the Cesium JS API. Following the online tutorial provided by Cesium, my process hits an unexpected roadblock when running the command "npm run build." The ...

Uh-oh, the Next.js fetch didn't go as planned. The error message

Currently, I am using Next.js 14 for my project. Suddenly, there has been an issue where some images are not loading on my local setup. However, the images load fine on the preview and production branches on Vercel. Upon checking my console, I noticed th ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Express file response problems affecting React front-end communication

I am currently developing a basic questionnaire on a React full stack website that uses React, Express, and SQL. Right now, my main goal is to return an error message from React and have it displayed on the front end. This is the code for my express endp ...

The save() function is not triggering the callback on a mongoose schema instance

I am encountering an issue while trying to save a JSON object in my database. The save() function is not triggering, and the JSON object remains unsaved. I suspect there might be a connection problem with Mongoose. Below is the code snippet showcasing the ...

Saving a promise object as a $scope variable in AngularJS: A quick guide

When working with my application, I use Constants.getContants as a promise to retrieve all the necessary constants. I want to store this information in a $scope variable so that it can be easily accessed throughout the controller or application. However, I ...

Is it possible to use JSON parsing with Swig in Node.js?

Recently, I decided to make the switch from Jade to Swig for my Express template engine due to Swig's exceptional performance. However, I encountered a roadblock when attempting to send an array of serialized JSON from Express into Swig and retrieve t ...

Tips for documenting curried functions using Js docs

I'm encountering issues while trying to use Js docs for generating static documentation of my project. When attempting to run the js doc command, I am faced with numerous parse errors specifically in areas where I have curried functions. Strangely, my ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

How do you retrieve the font-size value in percentages using jQuery's `css()` method for the element `e`?

When using the $(e).css('font-size')) method, how can I retrieve the font size as it appears (100% in my example)? It currently returns it as 100% of 16px which equals to 16px. jQuery ( function($) { alert($('div').css(&ap ...

Leveraging template's JavaScript within a React JS environment

I'm currently working on developing an application in React JS using an HTML/CSS/JavaScript template. My main focus right now is creating a navbar for the app, which involves incorporating several scripts into the code. I've encountered an error ...

Encountering the error message "Error: Unable to process rejection (TypeError): that.setState function is not defined" while using ReactJS

I've been working on a dynamic chart that changes based on the Slider value. I did some research and everyone suggests that I need to bind it to resolve this error. However, no matter how many times I try to bind the function in different ways, I keep ...