What is the best way to transform a Ruby hash into a JavaScript object while maintaining unquoted values?

Is there a way to display a Ruby hash as a JS object without quotes for certain values in the hash, essentially as JS code? For instance, consider the following Ruby code:

{ foo: proc { 'someJavascriptFn()' } }.to_json

How can I have the JS output as:

{ foo: someJavascriptFn() }

Is it possible to achieve this without making modifications to proc or hash?

Answer №1

Achieving this is possible, however, the creation of JSON will need to be done manually:

hash = {
  foo: proc { 'someJavascriptFn()' },
  bar: 42,
  baz: "Hello, world!"
}

content = hash.each_with_object([]) do |(k, v), acc|
  acc << ("#{k}: " << (Proc === v ? v.() : v.inspect))
end.join(",\n")
#⇒ "foo: someJavascriptFn(),\nbar: 42,\nbaz: \"Hello, world!\""
puts "{#{content}}"
#⇒ {foo: someJavascriptFn(),
#   bar: 42,
#   baz: "Hello, world!"}

Keep in mind that if your input contains nested structures, you may need to implement a recursive call to handle them.

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

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

Exploring the wonders of Lightbox when dealing with content loaded via AJAX

Using Bootstrap 5 along with the Lightbox library from , I encountered an issue. The Lightbox feature functions properly on regular page loads, but fails to load on content loaded via AJAX. I attempted to resolve this by implementing the following code: ...

What is the best way to center a heading element within a section on a webpage?

I need assistance aligning the h1 element with the specific class wish to the center of its section, both horizontally and vertically. Unfortunately, I have been unable to achieve this thus far. Any guidance would be greatly appreciated. Below you will fi ...

Setting a background image in ReactJS

I've been struggling with this issue for a while now, and after doing a lot of research online, I came across a solution that is supposed to work in index.css body { background-image: url(../src/components/images/photo.jpeg) no-repeat center cent ...

Issue encountered: Incompatibility between Mongoose Populate and Array.push()

After reading a different post addressing the same issue, I still couldn't figure out how to implement the solution into my own scenario. The discussion revolved around the topic of node js Array.push() not working using mongoose. In my Mongoose asyn ...

Tips for transferring the data from one yform value to another field

Within our online store, some products feature a yForm to consolidate various parts of the product. Is there a straightforward method to automatically transfer the sum field value to another field, such as the product quantity (which does not use yForm)? I ...

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

Conceal a div element after redirecting to a different HTML page

I have a dilemma with my two HTML pages - index.html and register.html. I am trying to navigate from index.html to register.html, but I want to skip the select region step and go straight to the login page. Here's the code snippet I've been attem ...

Tips for canceling an http request in angularjs when the requesting controller has exited its scope

Developed a custom angularjs application with ng-view for loading four different modules using route provider. Each module makes HTTP requests as shown below: var requestManager = { "locations": {}, "employees": {}, "items": {}, "templates ...

What is the best way to showcase a local image in the console using nwjs?

I am currently developing a desktop application using NW.js (node-webkit). In relation to this topic google chrome console, print image, I am attempting to display an image in the console. Following the suggestion from the aforementioned topic, the follo ...

Angular js is a powerful framework that allows for the seamless transition of views, except for the home

I am currently using the ng-animate module to implement sliding effects for my app views. Each route has its own unique slide animation. Take a look at my simple code below: HTML: <div ng-view ng-animate class="slide"></div> CSS: /*Animatio ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Struggling to make the fancybox feature function with html/php

I've been trying to find a solution to this problem repeatedly, but I just can't seem to crack it. All I want to do is use fancybox to display an image. Since this is my first time using fancybox, I'm sure someone with more experience will ...

Encountering a JSON gem installation error while running a bundle install command

Whenever I attempt to run a bundle install, I keep encountering this json error that prevents the installation from completing. What could be causing this issue? Errno::EACCES: Permission denied - /usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems ...

Live JSON sign-up feature on site

Is there a way to retrieve user email in real-time without using JSON? Currently, I am utilizing JSON for this purpose but it poses the risk of exposing emails that are stored in $resEmailsJson. Ideally, I would like to find a solution to hide all JSON $ ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

Issue with creating a variable name inside a JavaScript for loop

Here is the code snippet I am currently working on: var var1 = 58; for(var i=0;i<10;i++){ if(("var"+i) == 58) { console.log("they are equal"); } } I am wondering why ("var" + i) is not equal to 58 in this scenario. Could someone please provide an ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Exploring the differences between server-side rendering and client-side rendering in Express using Pug

I find myself in a state of confusion when it comes to distinguishing between what is considered client-side and server-side. Currently, as I develop a website using Pug for my HTML pages without any external files being loaded into the client's brows ...