Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails, appending jQuery Data

Is there a way of attaching data to elements in Rails like jQuery. For instance if you have

var element = $('element');
element.data('i', 'Hello world');

in jquery, you can retrieve that data later:

console.log(element.data('i));

will result in

Hello world

this way it stores the information in an obscure place resulting in a variable that isn't accessible from outside of jQuery directly.

In contrary, right now I'm only aware of appending HTML data attributes using Rails:

<%= content_tag(:div, "Something", data: { i: 'Hello world' }) %>

Which is equivalent of setting a .attr() in jQuery.

Setting HTML data attributes results in:

  • visibility on the elements upon inspection
  • cannot be objects

So essentially, what I'm trying to ask here is, can I append jQuery data set with Rails so it will be:

  • accessible only from .data()
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
like image 551
Bad Hombre Avatar asked May 24 '26 15:05

Bad Hombre


2 Answers

Is there a way of attaching data to elements in Rails like jQuery

Example:

# in your view *.html.erb
<%= content_tag(:div, "Content", data: { whatever: 42, whenever: "5pm" }) %>

Results in:

<div data-whatever="42" data-whenever="5pm">Content</div>
like image 116
user3680688 Avatar answered May 26 '26 03:05

user3680688


Option 1

Have a look at gon, which makes it trivially simple to access your Rails variables in JavaScript. It doesn't attach them as data attributes, but at the same time you are sending the data to the client all in one go, so it will be available in the page source.

(This Railscast episode also walks you through the setup, and how it works)

Option 2

If you really need the data to be hidden/obfuscated (I assume this is from scrapers, so that's what I'll focus on here), and you don't want to do this client side, then you'll need to set up a new route in your Rails application, and do AJAX calls to that endpoint to return the data. It's not foolproof, but there's options here to make things a bit more difficult for scrapers.

like image 40
gwcodes Avatar answered May 26 '26 05:05

gwcodes