Ignoring a line of HTML from a page cache - ruby-on-rails

Is it possible to ignore a line of HTML (in this case it's JS, but that's irrelevant) from a page cache?
To sum it up, I've got a page being cached using caches_page which in some cases the page is viewed with a parameter which sets off a trigger in JS. More specifically, there's an image viewer in there where the JS trigger is an index for the array of the slideshow. So if the param is there with, say, the value of "6" it'll go to the 6th image in the slideshow rather than starting from the beginning. Pretty straightforward stuff.
I would like to cache this page without the offending line of JS ( imgIndex(#) ). Any way to pull that off? If it makes any difference, and I know it might, I'm on Rails 2, not 3. Thanks.

You could use fragments cache instead. That way you can leave the JS and anything you want out of the important stuff.
Something like this:
# your JS and any content you don't wanna cache goes here or after the following block
<% cache do %>
<% #anything here will be cached %>
<% end %>

Related

React Component not rendered properly with Turbolinks in Rails 5.1

I have a very simple Rails app with a react component that just displays "Hello" in an existing div element in a particular page (let's say the show page).
When I load the related page using its URL, it works. I see Hello on the page.
However, when I'm previously on another page (let's say the index page and then I go to the show page using Turbolinks, well, the component is not rendered, unless I go back and forth again. (going back to the index Page and coming back to the show page)
From here every time I go back and forth, I can say that the view is rendered twice more time.Not only twice but twice more time! (i.e. 2 times then 4, then 6 etc..)
I know that since in the same time I set the content of the div I output a message to the console.
In fact I guess that going back to the index page should still run the component code without the display since the div element is not on the index page. But why in a cumulative manner?
The problems I want to solve are:
To get the code run on the first request of the show page
To block the code from running in other pages (including the index page)
To get the code run once on subsequent requests of the show page
Here the exact steps and code I used (I'll try to be as concise as possible.)
I have a Rails 5.1 app with react installed with:
rails new myapp --webpack=react
I then create a simple Item scaffold to get some pages to play with:
rails generate scaffold Item name
I just add the following div element in the Show page (app/views/items/show.html.erb):
<div id=hello></div>
Webpacker already generated a Hello component (hello_react.jsx) that I modified as following in ordered to use the above div element. I changed the original 'DOMContentLoaded' event:
document.addEventListener('turbolinks:load', () => {
console.log("DOM loaded..");
var element = document.getElementById("hello");
if(element) {
ReactDOM.render(<Hello name="React" />, element)
}
})
I then added the following webpack script tag at the bottom of the previous view (app/views/items/show.html.erb):
<%= javascript_pack_tag("hello_react") %>
I then run the rails server and the webpack-dev-server using foreman start (installed by adding gem 'foreman' in the Gemfile) . Here is the content of the Procfile I used:
web: bin/rails server -b 0.0.0.0 -p 3000
webpack: bin/webpack-dev-server --port 8080 --hot
And here are the steps to follow to reproduce the described behavior:
Load the index page using the URL http://localhost:3000/items
Click New Item to add a new item. Rails redirects to the item's show page at the URL localhost:3000/items/1. Here we can see the Hello React! message. It works well!
Reload the index page using the URL http://localhost:3000/items. The item is displayed as expected.
Reload the show page using the URL http://localhost:3000/items/1. The Hello message is displayed as expected with one console message.
Reload the index page using the URL http://localhost:3000/items
Click to the Show link (should be performed via turbolink). The message is not shown neither the console message.
Click the Back link (should be performed via turbolink) to go to the index page.
Click again to the Show link (should be performed via turbolink). This time the message is well displayed. The console message for its part is shown twice.
From there each time I go back to the index and come back again to the show page displays two more messages at the console each time.
Note: Instead of using (and replacing) a particular div element, if I let the original hello_react file that append a div element, this behavior is even more noticeable.
Edit: Also, if I change the link_to links by including data: {turbolinks: false}. It works well. Just as we loaded the pages using the URLs in the browser address bar.
I don't know what I'm doing wrong..
Any ideas?
Edit: I put the code in the following repo if interested to try this:
https://github.com/sanjibukai/react-turbolinks-test
This is quite a complex issue, and I am afraid I don't think it has a straightforward answer. I will explain as best I can!
To get the code run on the first request of the show page
Your turbolinks:load event handler is not running because your code is run after the turbolinks:load event is triggered. Here is the flow:
User navigates to show page
turbolinks:load triggered
Script in body evaluated
So the turbolinks:load event handler won't be called (and therefore your React component won't be rendered) until the next page load.
To (partly) solve this you could remove the turbolinks:load event listener, and call render directly:
ReactDOM.render(
<Hello name="React" />,
document.body.appendChild(document.createElement('div'))
)
Alternatively you could use <%= content_for … %>/<%= yield %> to insert the script tag in the head. e.g. in your application.html.erb layout
…
<head>
…
<%= yield :javascript_pack %>
…
</head>
…
then in your show.html.erb:
<%= content_for :javascript_pack, javascript_pack_tag('hello_react') %>
In both cases, it is worth nothing that for any HTML you add to the page with JavaScript in a turbolinks:load block, you should remove it on turbolinks:before-cache to prevent duplication issues when revisiting pages. In your case, you might do something like:
var div = document.createElement('div')
ReactDOM.render(
<Hello name="React" />,
document.body.appendChild(div)
)
document.addEventListener('turbolinks:before-cache', function () {
ReactDOM.unmountComponentAtNode(div)
})
Even with all this, you may still encounter duplication issues when revisiting pages. I believe this is to do with the way in which previews are rendered, but I have not been able to fix it without disabling previews.
To get the code run once on subsequent requests of the show page
To block the code from running in other pages (including the index page)
As I have mentioned above, including page-specific scripts dynamically can create difficulties when using Turbolinks. Event listeners in a Turbolinks app behave very differently to that without Turbolinks, where each page gets a new document and therefore the event listeners are removed automatically. Unless you manually remove the event listener (e.g. on turbolinks:before-cache), every visit to that page will add yet another listener. What's more, if Turbolinks has cached that page, a turbolinks:load event will fire twice: once for the cached version, and another for the fresh copy. This is probably why you were seeing it rendered 2, 4, 6 times.
With this in mind, my best advice is to avoid adding page-specific scripts to run page-specific code. Instead, include all your scripts in your application.js manifest file, and use the elements on your page to determine whether a component gets mounted. Your example does something like this in the comments:
document.addEventListener('turbolinks:load', () => {
var element = document.getElementById("hello");
if(element) {
ReactDOM.render(<Hello name="React" />, element)
}
})
If this is included in your application.js, then any page with a #hello element will get the component.
Hope that helps!
I was struggling with similar problem (link_to helper method was changing URL but react content was not loaded; had to refresh page manually to load it properly). After some googling I've found simple workaround on this page.
<%= link_to "Foo", new_rabbit_path(#rabbit), data: { turbolinks: false } %>
Since this causes a full page refresh when the link is clicked, now my react pages are loaded properly. Maybe you will find it useful in your project as well :)
Upon what you said I tested some code.
First, I simply pull out the ReactDOM.render method from the listener as you suggested in your first snippet.
This provide a big step forward since the message is no longer displayed elsewhere (like in the index page) but only in the show page as wanted.
But something interesting happen in the show page. There is no more accumulation of the message as appended div element, which is good. In fact it's even displayed once as wanted. But.. The console message is displayed twice!?
I guess that something related to the caching mechanism is going on here, but since the message is supposed to be appended why it isn't displayed twice as the console message?
Putting aside this issue, this seems to work and I wonder why it's necessary in the first place to put the React rendering after the page is loaded (without Turbolinks there was the DOMContentLoaded event listener)?
I guess that this has do with unexpected rendering by javascript code executed when some DOM elements are yet to be loaded.
Then, I tried your alternative way using <%= content_for … %>/<%= yield %>.
And as you expected this give mitigate results ans some weird behavior.
When I load via the URL the index page and then go to the show page using the Turbolink, it works!
The div message as well as the console message are shown once.
Then if I go back (using Turbolink), the div message is gone and I got the ".. unmounted.." console message as wanted.
But from then on, whenever I go back to the show page, the div and the console message are both never displayed at all.
The only message that's displayed is the ".. unmounted.." console message whenever I go back to the index page.
Worse, if I load the show page using the URL, the div message is not displayed anymore!? The console message is displayed but I got an error regarding the div element (Cannot read property 'appenChild' of null).
I will not deny that I completely ignore what's happening here..
Lastly, I tried your last best advice and simply put the last code snippet in the HTML head.
Since this is jsx code, I don't know how to handle it within the Rails asset pipeline / file structure, so I put my javascript_pack_tag in the html head.
And indeed, this works well.
This time the code is executed everywhere so it makes sense to use page-specific element (as previously intended in the commented code).
The downside, is that this time the code could be messy unless I put all page-specific code inside if statements that test for the presence of the page-specific element.
However since Rails/Webpack has a good code structure, it should be easily manageable to put page-specific code into page-specific jsxfiles.
Nevertheless the benefit is that this time all the page-specific parts are rendered at the same time as the whole page, thus avoiding a display glitch that occurs otherwise.
I didn't address this issue at the first place, but indeed, I would like to know how to get page specific contents rendered at the same time as the whole page.
I don't know if this is possible when combining Turbolink with React (or any other framework).
But in conclusion I leave this question for later on.
Thank you for your contribution Dom..

JQuery plugin initialization on browser back button for Turbolinks Rails 5

Whats a better solution for initializing jquery plugins on browser back button that aren't just transforming elements when using turbolinks in Rails 5 like masterslider (photo gallery) or slick (carousel), than reloading the page as I do below?
document.addEventListener 'turbolinks:load', ->
slickElementsPresent = $('.event-card').find('div.slick-slide')[0]
if slickElementsPresent?
window.location.reload();
else
$('.event-card').each ->
$(#).not('.slick-initialized').slick {
infinite: false,
nextArrow: $(#).find('.event-more-details-button'),
prevArrow: $(#).find('.event-card-slide-back-button')
}
To be clear, I check to see on 'turbolinks:load' if there are any html elements that would only be present if the plugin had been initialized, if so, then refresh the page because even though the elements are there, the plugin isn't initialized. And then I initialize the plugin on all the elements that have the class I want it on.
Some people encountered this problem here: https://github.com/turbolinks/turbolinks/issues/106 where someone points out
I just want to add for those having similar issues that making an initialization function idempotent is not necessarily the solution in some circumstances. Having done so with dataTables I am able to avoid duplicate elements. However, the cached versions of the elements on the page related to the plugin no longer function on a browser back click as it seems the plugin is not initialized in a cached page.
Reloading the page if the plugin has already changed the DOM because it's being retrieved from the cache when someone presses the back button just seems pretty bad, but its the best I've come up with so I'm turning to the world for more ideas!
UPDATE:
So some jquery plugins have great 'undo'/'destroy' methods and if that's the case it's better to add an event listener on "turbolinks:before-cache" and then call that method like so:
document.addEventListener "turbolinks:before-cache", ->
$('.event-card').each ->
$(#).slick('unslick');
but some jquery plugins do not have destroy functions or destroy functions that achieve this. Like masterslider has a $('your-slider-element').masterslider('destroy') function, but it doesn't 'undo' the javascript magic it applies to your html so much as just getting rid of it entirely, and so when you come back to the page from the browser back or forward button, the slider simply doesn't exist, because the html element it gets triggered on has been destroyed. That means for some plugins, the best answer I still have is to reload the page entirely when the page they are on is navigated to via the browser back and forward buttons.
So the best answer I've come up with for dealing with 'Restoration' visits (as I have since learned browser back and forward button visits are called in the world of turbolinks) that involve jquery plugins that don't have an 'undo' method is to simply opt the page out of cache-ing. I implemented this by throwing:
<% if content_for?(:head) %>
<%= yield(:head) %>
<% end %>
in the <head> section of my application.html.erb file and then at the top of the page I don't want turbolinks to include in it's cache, I put:
<% content_for :head do %>
<meta name="turbolinks-cache-control" content="no-cache">
<% end %>
That way turbolinks fetches the page from the network and not the cache as would be the normal behavior for a 'restoration' visit. Just had to read the documentation very carefully and figure out how to implement it in rails which wasn't too bad.

Caching DOM changes in rails

I am conducting partial caching which is working really well.
However if I change the DOM inside the cache block those changes arn't cached. Is there a way to also include those changes?
Here is what I have so far:
<%
cache(#contact.hash_key) do
%><div id="<%=#contact.hash_key%>"></div><%
end
%>
<script>
//use ajax to prepend new messages.
$(document).ready(function(){
$.get("/messages?cid=<%=#contact.hash_key%>", function(data) {
$("#<%=#contact.hash_key%>").prepend(data);
});
});
</script>
UPDATE
Ok so I am trying to attempt to cache the result before it enters the DOM with the same cache key. That way when the cache block is rendered the new data is included with that key.
But I'm not sure the correct way to structure this.
Done!
So for anyone wanting to do the same thing here is a brief outline on how to do it. You may need to make changes or tweak this solution to fit your own.
This will only work if you are using cache keys. In my instance I have 2 types. A contact.hash_key and a message.hash_key
All message caches are kept inside a parent contact cache. So essentially:
<div id='contact-hash'>
<div id='message-hash-1'>
<div id='message-hash-2'>
<div id='message-hash-3'>
First of all we need to loop through the messages and see if they are cached. If they are then you can just render the cached copy. You can do this by using the Rails.cache.read method:
messages.each do |message|
cache = Rails.cache.read 'views/'+message.hash_key
if cache.nil? == false
%><%= cache.html_safe %><%
end
end
So now we have a list of messages from cache thats already been loaded. So what about new messages? Lets load these via ajax so the user isn't waiting for a boring page load.
You will notice in my question above I have querying "/messages?cid=<%=#contact.hash_key%>" in my AJAX call. This is calling the messages controller and rendering the index view.
Before we want to load the rendered view into the DOM we want to write it to the cache first with, surprise surprise, the identical message.hash_key we are going to use to read it.
So in your view:
<%
cache(message[:hash_key]) do
%>
<div class='message'>
This is a new message from the server.
</div>
<%
end
%>
If in some situations this doesn't work (god knows theres so many app permutations out there) you can also use Rails.cache.write 'foo', 'bar' in the controller instead of caching it at the view level.
And there you have it. Now you can add the new hash_key to the list and then render the view back to the DOM as the results of your AJAX call.
Now with the new hash_key in the list you can loop over it and it will come up as a cached copy.
This may or may not be the most elegant solution. If someone wants to simplify or give any advice on it so I can improve it that would be much appreciated.

ruby rails print specific elements from multiple partial files residing in a directory

I have a directory filled with partials. I'm looking to list ONLY the first h1 tags in each partial. The methods to accomplish this task could probably be modified to grab other elements as well.
Right now I use ruby to open each file, print out the first few characters, close file, and repeat. My ruby file parsing skills are limiting me. Here's the code I have at the moment:
<% Dir["app/views/partials/show/*.html.erb"].each do |f1| %>
<% aFile = File.open(f1, "r") %>
<% if aFile %>
<% content = aFile.sysread(20) %>
<p><%= content %></p>
<% else %>
<%= "Unable to open file!" %>
<% end %>
<% end %>
I also think I'm opening the entire partial in memory? Wondering If I can just read up until I find my h1 tag then close file and move on? Again I'm only reading first 20 characters because I haven't yet grasped a way to search for the first h1 tag.
I'll make edits as I work through the open, parse, piece... I appreciate any guidance and direction you can offer. Thanks!
EDIT:
Based on comments below there may be a far better way to accomplish my task. So I'm providing some additional background to get direction on other solutions.
This is for a slide show based on partials in a directory. The slide show is controlled with a navigation element which I would like to populate by the h1 tags in the partials. I'm not going to manually enter these things every time a change is made! I want the end user to simply drag and drop partials into a directory (with a certain name convention and h1 tag description for navigation) and let the slide show do everything else.
I could impose a class on the h1 tag "forNavigation" and on the content "sliderContent" and then use jquery to create a post load <ul> but that doesn't seem right. Plus they'll all be part of the same rendered div.
I guess I'm not clear why reading the first 50 characters of a partial, copying whats in the h1 tags, and putting it in a isn't the most elegant solution?
Like I said, above does everything needed except copy and print whats between the first h1 tag... With an xml parser or some regexp it'll be done. I'm just no good with parsing files.
Please let me know other methods to approach this. Right now I still think it's best to parse the partial (with or without rendering) and put what I need where I want it as needed.
Partials are not meant to be "parsed", but to be rendered inside other partials and templates. If you need to grab a part of a partial, you should probably extrat that part as a further partial, and use that inner partial in both the "listed" partial and in the "aggregated" view.

can link_to lead to rendering sth?

i want to render a partial within a view. so that when button MORE is clicked everything stays the same just additional characters are shown. in my case the whole article.
<%= #article1.content[0..300] + "..." %>
<%= link_to "more", ....... %>
i dont know what the right methot would be. somehow i have to explain to rails that when button more is clicked it shows me the whole article. maybe i shouldn't use method link_to ..
thank you in advance for your replys
What you're looking for is link_to_remote or link_to_function.
link_to_remote will be fetching the rest of the article from your controller and replacing/appending to a DOM element with a partial via RJS. This allows you to minimize unnecessary data being sent, and facilitates handling users that have javascript disabled.
With link_to_function, the entire article will be served when the page is loaded, but the everything beyond the first 300 characters will be hidden by CSS. This is easier to set up but sends a lot more data, it also relies on the user having javascript enabled.
Without looking at the source the average user probably couldn't distinguish between the two methods.
Which choice you go with is up to you. Sorry, I haven't got time to provide code examples, but the internet is full of them.
try link_to_function, use truncate for part and insert hidden tag with full text, switch them using javascript in link_to_function

Resources