How to separate javascript libraries and calls in the Rails 3.1 asset pipeline - ruby-on-rails

I'm trying to get the hang of the whole asset pipeline thing, and read the guide and several tutorials about them. But one thing that doesn't become quite clear is wether I should view my javascript asset files as a library or a place to put code that is actually run i.e. $(document).ready. Because by default all the javascript files are included, and it would be weird to have several $(document).ready's in there, not to mention that you don't want the $(document).ready function for every page to be run in the first place. What would be the way to go at this? Use my asset files as a library and put actual calls in my views (ugly)? Or is there a better way to do this?

I too ran into this issue. In a large project you can have somebody put code into document ready to, for example, add a click function to each li within a div with class container.
Now we could all argue that the above code would be too generic and of course may affect li tags in other parts of the application, but the bigger the project, the more likely it is that you will run into a conflict like this leading to unexpected behaviour.
I for one am uncomfortable with a whole bunch of document ready functions running for each and every page loaded. My solution is not necessarily the perfect one, but it's one that I have taken up and will share with you.
In the body tag of each page I add data elements signifying the controller and the action. I then have one document ready script that looks for a class named after the controller with the name Ready appended e.g. HomeReady. It will then call a method on this class (presuming it exists) named after the action. So in your asset coffee file you could write:
class #HomeReady
#index: ->
alert("Hello")
#show: ->
alert("Goodbye")
This allows control right down to the action level. When I came across your question I decided to package this solution into a gem as I have already used it in several projects. You can find it at: https://github.com/intrica/rails_document_ready

If you absolutely don't want a certain piece of initialization code to be run unless the current page is a specific controller/action, then you can try adding an empty element on the page with an id built from that info like "posts_index" using these two helpers:
"#{controller_name}_#{action_name}"
Then in your javascript you can wrap the code inside an if statement that checks for the existence of an element with the appropriate id.
edit: Here's an example of the js partial that I mentioned in the comments.
show.html.haml
= render 'map'
map.html.erb (I normally use haml but it's easier to write js in erb)
<script src='http://www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
...
</script>
It's probably not as clean as it could be and it doesn't get the benefits of being part of the asset pipeline but I don't mind because it's only something that gets included on a specific page.

Related

Applying a master page template in Sling with HTL

Is there any simple way to apply a page template to multiple Apache Sling scripts?
I'm looking for something akin to the JSP 2.0 Tag option. However, I'm using HTL, which doesn't support such tags.
I could, of course, use HTL includes, such as data-sly-include="${'header.html'}, but these would then have to be manually included in every page I then create.
Ideally I'd like to be able to have a master page containing the layout, which is then automatically applied to all pages of specified resource types, leaving a customisable area for content specific to each resource. I'd then be able to limit my add.html, edit.html, html.html (etc) files to include only a block of code for the content section of the page, preventing unnecessary duplication of layout code across multiple files.
I thought I might be able to achieve this by creating a master page resource (e.g. "page"), then setting sling:resourceSuperType on the individual resources but since this acts as a fallback, it'll only kick in if there's no matching script for the sling:resourceType - and there will be such scripts.
You could use a Sling Decorator to wrap your resources so that they always get handled by the common scripts before everything else. This way you can impose the template and include the actual resource to fill in the actual values/blocks/custom scripts.
Another option would be to impose a (nested) content tree where the root points to the template scripts (using JCR type, for example) while the children/content point to the custom scripts (using resource type). This is pretty much what AEM does with cq:Page and its jcr:content.
I ended up using the following approach:
Add a new resource type page
Create a Sightly/HTL template file for the page resource type (/apps/page/html.html); this is the 'master' page template
Include common elements in that template
Within that template, call the 'child' templates by adding the view selector through the following HTL element: <div data-sly-resource="${request.pathInfo # selectors='view', addSelectors=request.requestPathInfo.selectors, requestAttributes=request.requestParameterMap}">
For each sling:resourceType that's to be rendered as a page, add a view subfolder (/apps/example_type/view) and place its HTL templates within that folder (e.g. add.html, html.html)
On each resource that should be rendered with the master template, set sling:resourceSuperType to page
When a request comes in to, for example, /content/example_type_instance.add.html, Sling resolution will therefore try to find a script in /apps/example_type/add.html; there isn't one, so it falls back to the resourceSuperType script in apps/page/html.html, which in turn will use the script in /apps/example_type/view/add.html.
This seems to work for the moment. #Vlad's approach with a Sling ResourceDecorator may be more elegant.

Can I make a partial template that have readonly fields when used by show and not when used by edit and create?

I've partial templates that are used by the show, edit and create form.
In the show-form I don't want them editable, it can be confusing for the user.
Is there a simple solution for this otherwise I need a different template for the show-form or... why use a template then.
I've tied this and created 2 scripts, one that disables and one that enables.
Script 1.
$(document).ready(function(){
$('.elements').attr('readonly',true);
$('.elements').prop('disabled',true);
});
Script 2.
$(document).ready(function(){
$('.elements').attr('readonly',false);
$('.elements').prop('disabled',false);
});
Then I stored those scripts in assets\javascript.
It worked good in show but both edit and create went read-only too.
It seems like everything that is put in this directory is automatically used in each form, because even though I removed the call from the forms, it was working.
Here I show where I originally added the script-call:
<asset:javascript src="myScript_1.js"/>
</body>
</html>
I was going to add it as a comment but then it started to get long and complicated to follow.
why store it in assets ?
simply add a function block to the templates that need it
_template1.gsp
<script>
$(document).ready(function(){
setReadOnly('${someDefinition}')
function setReadOnly(value) {
if (value==='READONLY') {
$('.elements').attr('readonly',true).prop('disabled',true);
}
}
})
</script>
If this function needs to be shared by a bunch of pages, you could add it to an assets / javascript file but rather than declare it in application.js call the js file <asset:javascript tags specificially on each page
and maybe a variable that you pass to template to say when it should be called
or put that above template1 as a master template and call in each of the other templates that needs the js file (So many options)
Now on the main controller doing action
def MyController {
def view() {
String mode='READONLY'
render view: 'index', model:[instance:params,mode:mode]
}
}
the in index.gsp
if js is there then it will pick up mode and set readonly for that controller action or pass that from one template to another, the controller does not have to define actual mode, the main master view page or index page could define mode too
Maybe you need to play/understand then implement you can't rush these things otherwise you will end up wasting time and rewriting
Just to ensure we are on the same page.
By default the application.js file in the javascript folder has a tree line enabled - this by default then reads in all js files. If you wish to manually call js in different places you will need to remove this line and declare each and every js file that you use like the other lines provided in that file.
So that is the price to pay (no more auto loading js files) until declared in application.js
But then most importantly as you have noticed these are global js functions and really nothing new should be going in there that hasn't got a function something() { } a function call.
They will then react when the actual function is called rather than how you had it which was open for call from any old page since it happened as documents opened regardless

How to keep related Partial page/HtmlHelpers, scripts and css together and not separate references

I have a form that has a button next to person textbox that brings up a person Bootstrap Modal Search Window.
the html I put in a partial page and reference it
#{await Html.RenderPartialAsync("_PersonControlPartialHtml","PersonControl1");}
#{await Html.RenderPartialAsync("_PersonControlPartialHtml","PersonControl2");}
which adds a textbox and button.
Then I add a bootstrap modal html to the page that only has to appear once per page
#{await Html.RenderPartialAsync("_PersonControlModal");}
Then the javascript event code and css for the above.
#section Header {
<script src="~/css/personcontrolscript.css"></script>
}
and
#section Scripts {
<script src="~/js/personcontrolscript.js"></script>
}
The html I could put in an htmlhelper but I still need to add 3 references to the page if I want to add it to a page.
Is there not an easier way?
There are ways to reduce this but those ways come with trade offs. So it really depends on which approach best fits your needs.
So for example you could eliminate adding the .css reference in the header section via two different approaches:
1) you could place those styles in a global.css file that is already loaded for ever page; or
2) you could use inline styles on you html and eliminate these css classes.
Both of these solutions of course have downsides. Approach one means that the size of the global.css styles will be larger and take a bit more time to load even if the first page used on the site doesn't need them. Approach 2 seems to fly in the face of conventional wisdom that you should almost never use inline styles and it will make the markup more verbose. But either solution would allow you to eliminate the need for including a seperate ~/css/personcontrolscript.css reference every time you have a person control on the page.
As for the need to include ~/js/personcontrolscript.js, that could be solved one of two ways:
1) include the javascript code in a global.js file that is loaded for every page; or
2) put that javascript code inline in the _PersonControlPartialHtml and add code to it to make sure that it only gets injected the first time the partial is used on the page.
As for the bootstrapModel, I'm a little less clear on what that code looks like so I can't say for sure but probably it could leverage an approach similar to one mentioned for css or js.
With regard to rendering your partials, I don't think there is any way to eliminate that given that it's the primary representation of the functionality you are adding to the page.

Instance variables in controller passed to bootstrap file input plugin

I'm using bootstrap3 and a particular plugin for bootstrap called file-input. I'm using file-input and paperclip to attach a picture of a restaurant to my Restaurant model.
One of the things I would like to do is have the ability for my users, when editing a restaurant image, to be able to see the old restaurant image (which is stored in #restaurant.image.url). After reading the documentation, I found that I can set a default image to file-input by passing in a source like so:
initialPreview: [
"<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>",
"<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>",
],
What I'm stuck on is how do I get my #restaurant.image.url into the src attribute of a javascript array, that I can then pass on into the file-input plugin.
I found this question and it made it seem like if I turn my restaurant.js file into a restaurant.js.erb file I can just use ruby expressions.
javascript
("#image_upload").fileinput( initialPreview: ["<img src='<%= #restaurant.image.url %>' class='file-preview-image'>",]);
But #restaurant is blank in my javascript file. Anyone know why?
I am using rails 4, I don't know if that is the difference.
First and foremost, files located in the asset folder don’t have access to instance variables defined in the controller. However, views invoked by your controller do. One simple solution (although rails purists might behead me) would be to inline the javascript directly into your form partial.
in your _form.html.erb
<script>
$(document).ready(function(){
img_source = "#{defined?(#restaurant) && #restaurant.image.exists? ? #restaurant.image.url : image_url('default_image.jpg')}"
$("#image_upload").fileinput( initialPreview: ["<img src='"+img_source+"' class=\'file-preview-image\'>"]);
});
</script>
Note: I did add a default image (since you are using paperclip); modify accordingly.
More complicated solutions might involve gems such as gon which can help you pass variables to javascript functions.

Still having a hard time with RoR MVC approach

I suppose it should do justice to state what I think I know so far as well as what I've done:
1) I created the app and did my first db migration; I now have my dev, test and production databases. The dev db has a table called 'wines'.
2) I made a scaffold which created the necessary files.
3) The basic index/update/destroy methods are set up and I can browse the pages.
4) From what I gather, the ActiveRecord class "Wine" automatically inherits properties from the database? Each column is a property and each row in the table 'wines' is a potentially instantiated object which is called from the wine_controller script.
The problem I'm having now is that I want to create a common layout that all controllers use. The only things that will change will be the page title, potentially some <link> tags in the header, the <body> attributes (javascript onload events most likely) and whatever lies inside the <body> tag.
I find myself looking up functions that will do what I want (like "favicon_link_tag", "stylesheet_link_tag" and "auto_discovery_link_tag"...) but I can't find the right place to PUT them! I know this has something to do with my lack of understanding of how things are executed/inherited. For example if I were to declare #pageTitle in application_controller.rb and use #pageTitle in ApplicationHelper it won't work. Or even using "stylesheet_link_tag" in application_controller.rb throws an error. I'm just not getting something.
How does each thing relate to another in terms of chronological execution, scope, etc.?
In your "app/views" directory there is a folder called "layouts." By default there should be an "application.html.erb" file in there, but if there isn't you can create it.
Your "application" layout file is the default layout file used by any view. However, if you want a particular controller to use a different view, you can override this. See this railscast, and this one is helpful too.
The main thing to understand is the content from any particular view will show up wherever the yield method appears in your application layout. The main 'yield' block gets the view file specified by your controller action, but you can mark anything inside any view to be passed to another yield block instead. For instance, the "title" example you gave could be passed to the head of your application layout. See this railscast for a detailed example of that.
For more, you should read the Rails Guide, and you might want to consider picking up a Rails starter book.
I got my feet wet with "Beginning Rails 3," which was a phenomenal introduction to the framework. A couple days with that book and it was all making sense to me, and I was developing faster than I ever had before. Rails rocks once you get to know it, but it's definitely worth going through a book.
Please continue to ask questions, I'll help if I can :)
-EDIT- To answer your question about control flow, it basically works like this:
Your browser sends a GET request for a particular URL.
The router takes that request, matches it to a controller action, triggers that controller action, and provides the controller any parameters associated with the request. For instance: if you requested example.com/posts/123?color=red this would trigger the SHOW action of your posts_controller, and would pass {:color => 'red'} to the params hash. You would access that using params[:color]
The controller action does its thing, and when it's done it renders output. By default it renders whatever view is located in app/<controller_name>/<action_name>, and will whichever file matches the extension appropriate to the request (ie an AJAX request would trigger <action_name>.js.erb and a GET request would trigger <action_name>.html.erb.
You can override this using the render method, for example by passing render 'foo/bar' to render using the view for FooController, Bar action instead of your current action.
Note that no matter what you render, the data available to the view is whatever is in the specific controller action the router triggered, not the controller action that would 'normally' render that view.
The view file is parsed using the data from the controller that called it. If you have any content_for methods then the view code that is inside the content_for block will go where you tell it, otherwise everything else will go to the main YIELD block in your application layout (or whatever layout your controller specified instead).
The application layout is parsed, and the content from the view is inserted into the appropriate areas.
The page is served to the user.
That's a simplification in some ways, but I think it answers your question. Again, feel free to keep asking :)

Resources