Generating dynamic CSS using templates - ruby

I want to generate dynamic CSS using templates and Tilt andSASS in Rails 4.
Let's say I have the following css.sass template:
$class_name: test
$width: 329
$height: 425
.view-#{$class_name}
width: #{$width}px
height: #{$height}px
I need master.css.sass.erb (I am not sure about the format) in which I am going to render my template as many times as I like with different parameters.
In application.css, I am going to have something like this
*= require master.css.sass.erb
Each time I use the template with different parameters, I am going to add a line in my master.css.sass.erb file. I do not know how to pass parameters using Tilt to the css.sass template. Could anyone assist and tell if this is possible?
This is what I have till now:
The template test.css.sass.erb:
$color: <%= color %>
body
background: #{$color} !important
The master.css.sass.erb file:
<%
require 'erb'
config_path = File.expand_path("../test.css.sass.erb", __FILE__)
template = Tilt.new(config_path)
template.render(self, :color => 'yellow')
%> .thisisrendered
color: red
Note that the two files in one folder. The issue is that only the following css is renrered:
.thisisrendered
color: red

To answer your question: when erb is compiled, it only outputs ruby code contained in a <%= code %> wrapper. Your current code is probably running fine (I'm not familiar with Tilt or straight SASS), but you aren't telling it to output the result to the sass file. Change the first line of master.css.sass.erb from <% to <%= and then you can debug from there.
That being said, I would recommend against this process. You're going to be wasting resources compiling the stylesheet every time it is called.
An alternate method would be to just keep your stylesheets static as in your opening example so they can be precompiled and cacheable, and then create a partial like layouts/_conditional_styles.html.erb using stock html and css like:
<% unless #your_sanitized_style_object.nil? %>
<style>
body{
background: <%= #your_sanitized_style_object.background_color.html_safe %> !important;
}
</style>
<% end %>
Which could override the application stylesheet by being rendered after the application css file in your layouts/application.html.erb file such as:
<%= stylesheet_link_tag "application" %>
<%= render "layouts/conditional_styles" %>
To answer your question as to why you use less resources using precompiled assets and then overriding them, consider your example test.css.sass.erb
$color: <%= color %>
body
background:$color !imporant
Assuming the color variable is red, the process would go something like this... First your application will run through it with its erb compiler and give you a test.css.sass file such as:
$color: #ff0000
body
background:$color !important
Then your application will run through the code again with its sass compiler to give you a test.css file such as:
body{ background:#ff0000 !important; }
And after all of that, it will serve up the file. In your development environment you will not see that much of a performance difference as your application defaults to rebuilding the assets for every request. The difference comes when it's time to serve your application to the web in production.
If your assets aren't dependent on variables in the application, the stylesheets can be precompiled. What this means is that your application compiles the asset once, and after it compiles the asset you get a stylesheet like test-f25ab2b1286feb7cc98375sac732f7d0.css.
The stylesheets will be identical but what is unique is all that jargon that rails throws on the end of the file name when it precompiles something. That jargon is known as a fingerprint and its purpose is to tell the server on an incoming request whether or not there is a newer version of the file. If the file hasn't been modified, and the system making the request has already downloaded that file to its cache, then your browser will use the cached version instead of downloading the stylesheet over again.
Now lets say your test.css.sass.erb file is something huge like 50kB for example's sake.
Without precompilation your resource cost is:
having to traverse that 50kB file 2 times on every request to compile it from erb > sass > css
having to serve up that 50kB file on every request.
With precompiled assets that are overridden by conditional styles embedded in the html of the layout as explained in my first answer:
Your compilation cost goes down to almost zero because the stylesheet is precompiled so there's nothing to do to it and your whatever.html.erb template that contains the conditional styles is already being compiled by your erb compiler so you're just adding the work of rendering variables.
You only serve up the precompiled stylesheet once meaning you save ~50kB in bandwidth on every request, using only the bytes needed for the rendered dependent styles.
Hope this helps, for more information on how all of this works I would recommend starting with the Asset Pipeline Rails Guide.

Related

How to call js and css files inside a html.erb file

I'm quite new to Ruby and ERB and for this case I'm using only Ruby and not rails.
E:\ruby
-app.rb
-plan.html.erb
-check.css
-track.js [js + jquery framework]
Inside app.rb I've the following lines
text = File.open(("final.html"), "w+")
text.puts ERB.new(File.read("plan.html.erb")).result binding
I'm not sure how to call the .js and .css files inside the .html.erb file. Kindly let me know if I've to post the .html.erb file in case that would be helpful to debug further, thanks.
You can include the JavaScript in the .html.erb file in the same way you load the text file. The simplest (code wise) solution is doing something along the lines of this:
plan.html.erb
<script>
<%= File.read('some/file.js') %>
</script>
However if you are expecting a <script src="some/file.js"></script> as result you'll have to create your own helper or use an existing one from some light weight web framework. A simple example might be:
lib/html_helpers.rb
require 'builder'
module HtmlHelpers
def javascript_include_tag(path)
Builder::XmlMarkup.new.script('', src: path)
#=> %{<script src="#{html_escaped_path}"></script>}
end
end
plan.html.erb
<% require 'html_helpers' %>
<% include HtmlHelpers %>
<%= javascript_include_tag('some/file.js') %>
Keep in mind that the first solution doesn't escape any HTML characters. Meaning that if your script contains </script> everything following that tag will be interpreted as HTML.

Ruby: how to generate HTML from Markdown like GitHub's or BitBucket's?

On the main page of every repository in GitHub or BitBucket it shows the Readme.md in a very pretty format.
Is there a way to make the same thing with ruby? I have already found some gems like Redcarpet, but it never looks pretty. I've followed this instructions for Redcarpet.
Edit:
After I tried Github's markup ruby gem, the same thing is happening.
What is shown is this:
And what I want is this:
And I'm sure it's not only css missing, because after 3 backquotes (```) I write the syntax like json or bash and in the first image it is written.
Edit2:
This code here:
renderer = Redcarpet::Render::HTML.new(prettify: true)
markdown = Redcarpet::Markdown.new(renderer, fenced_code_blocks: true)
html = markdown.render(source_text)
'<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>'+html
Generated this:
Github provides its own ruby gem to do so: https://github.com/github/markup.
You just need to install the right dependencies and you're good to go.
You need to enable a few nonstandard features.
Fenced code blocks
Fenced code blocks are nonstandard and are not enabled by default on most Markdown parsers (some older ones don't support them at all). According to Redcarpet's docs, you want to enable the fenced_code_blocks extension:
:fenced_code_blocks: parse fenced code blocks, PHP-Markdown style. Blocks delimited with 3 or more ~ or backticks will be considered as code, without the need to be indented. An optional language name may be added at the end of the opening fence for the code block.
Syntax Highlighting
Most Markdown parsers to not do syntax highlighting of code blocks. And those that do always do it as an option. Even then, you will still need to provide your own CSS styles to have the code blocks styled properly. As it turns out, Redcarpet does include support for a prettify option to the HTML renderer:
:prettify: add prettyprint classes to <code> tags for google-code-prettify.
You will need to get the Javascript and CSS from the google-code-prettify project to include in your pages.
Solution
In the end you'll need something like this:
renderer = Redcarpet::Render::HTML.new(prettify: true)
markdown = Redcarpet::Markdown.new(renderer, fenced_code_blocks: true)
html = markdown.render(source_text)
As #yoones said Github shares their way to do it but to be more precise they use the gem "commonmarker" for markdown. Though as far as I can tell this thing does not give the full formatted HTML file but only a piece that you insert into <body>. So you can do it like I did:
require "commonmarker"
puts <<~HEREDOC
<!DOCTYPE html>
<html>
<head>
<style>#{File.read "markdown.css"}</style>
</head>
<body class="markdown-body Box-body">
#{CommonMarker.render_html ARGF.read, %i{ DEFAULT UNSAFE }, %i{ table }}
</body>
</html>
HEREDOC
Where did I get the markdown.css? I just stole the CSS files from an arbitrary Github page with README rendered and applied UNCSS to it -- resulted in a 26kb file, you can find it in the same repo I just linked.
Why the table and UNSAFE? I need this to render an index.html for Github Pages because their markdown renderer can't newlines within table cells, etc. so instead of asking it to render my README.md I make the index.html myself.

Templating JavaScript and CSS files with TAL

Is it possible to template JavaScript or CSS files with TAL?
(or maybe there is some other templating mechanism in Zope exists)
e.g. templated CSS file will be something like that:
#button {
background-color: <%= buttonColor %>;
background-image: <%= buttonImage %>;
}
If you are using Zope2, use DTML. TAL/ZPT is only appropriate for HTML/XML/SGMLish markups.
If you are using browser views, you can also choose to use any Python-based template system, should you be willing to take care of rendering the template in your view's index() (or __call__()) method.

Grails Resources plugin, modules and <r:img> to render images?

trying to learn the Resources plugin
From my understanding, it helps to define 'resources' such as css and javascript files and automatically pull them into your gsp's when needed. I understand how to create modules that can then be loaded in using tags etc.
The part im not understanding is this: http://grails-plugins.github.com/grails-resources/guide/4.%20Using%20resources.html#4.2%20Linking%20to%20images
So ive created a module called 'images' in Config.groovy as follows:
grails.resources.modules = {
images {
resource url:'/images/view.jpg', attrs:[width: 1280, height:720 , alt: 'my view']
resource url:'/images/breakfast.jpg', attrs:[width: 1280, height:720, alt: 'breakfast']
}
}
The resources are included in the .gsp page in the head section as follows:
<head>
<r:require modules="jquery-ui, blueprint"/>
</head>
i know the resources have been successfully added to the head section because when i inspect the page source i see them there:
<link href="/ResourceTest/static/Aa7jV0N2qZjOz7TLZ9cl5cREIh2y5jJYV0ytn4nQg9r.jpg" rel="shortcut icon" width="1280" height="720" alt="my view" />
<link href="/ResourceTest/static/IpQBSjrYeLDdSUBGbP3jhf6Kkhvu1zV3XRtwWfKOIMn.jpg" rel="shortcut icon" width="1280" height="720" alt="breakfast" />
My question is this: how are the image resources then used? i mean i know if it was javascript, the importing of the resource gives you access to use the functions in the html code, but with regards to images, the site says "Once you have done this, using to reference them would automatically set the width, height and other attributes."
How? I've tried the following:
<r:img module="images">
<r:img alt="breakfast">
and a handful of others with no success
what does work is:
<r:img uri="/images/breakfast.jpg">
but this works regardless of whether or not you add the module with the r:require tag.. So whats the point of using this plugin for images then and how would i use it?
The <r:img> tag works just fine with our without <r:require>; it even works with undeclared image resources.
The point of the require tag is to prevent resource duplication. So, for instance, suppose you have multiple javascript resources that rely on jQuery, and they're all required. Add another layer of complication: say you're actually pulling together different gsp templates via sitemesh, and they each have their own resource dependencies. If you just put the normal HTML code to reference those resources in the head of each gsp layout, you might get multiple instances of them in your page header, which could prove problematic. Using the resources plugin makes sure you only get one instance of the required resource.
See http://grails-plugins.github.io/grails-resources/ref/Tags/require.html and http://grails-plugins.github.io/grails-resources/ref/Tags/layoutResources.html.
With images, though, this is not really necessary. If you have an image more than once on a page, it's probably because you wanted it, or because you're applying redundant layouts and need to refactor a bit. So, you are correct that the require tag doesn't really do much for images called via <r:img>. This is simply because images are a different sort of resource, so they're treated differently. Don't sweat it. :)

Rails 3.1 - Fancybox

I'm trying to get fancybox (technically fancybox-rails) working in Rails 3.1. I started with the directions here ... https://github.com/hecticjeff/fancybox-rails and then after quite some time discovered that I needed to add
<%= javascript_include_tag :application %>
to get things working (as an aside, why is the new asset pipeline better than just putting a javascript file in a known directory and using a javascipt_include_tag?). Anyway, now I'm not quite sure what to do. First is the css file for fancybox. Is this included somehow already? Do I have to do something similar to the above for the asset pipeline (I believe it's supposed to handle css files also). Finally, here's what I'd like to have "lightboxed" ...
<% #image_files.each do |image_file_name| %>
<%=link_to(image_tag image_file_name, :class=>"fancybox", :size => "200x200") %>
<% end %>
I have some images (jpg) in a directory pointed to by the image_file_name. These are showing up fine, but I'd like to be able to click on them and get the light box effect. So ... what does my link_to/image_tag need to look like?
Am I missing anything else here?
------- Added information --------
I should not that I do have some javascript for this ...
$(document).ready(function(){
// $("a img.fancybox").fancybox({'type': 'image'});
a#single_image").fancybox({'type': 'image'});
// $("$("a:has(img)").fancybox();
});
trying a few different things here and none seem to do much. I also added the following in the html just to simplify things with the Rails stuff ...
<a class="single_image" href="/assets/card_images/birthday_cake.jpeg"><img src="/assets/card_images/birthday_cake.jpeg" alt=""/></a>
The image shows, but when I click on it, it just goes to a page showing the image. I also checked and it looks like the css is there based on this ...
puts Rails.application.assets['jquery.fancybox.css'].body
which gave me something that started with this ...
/*
* FancyBox - jQuery Plugin
* Simple and fancy lightbox alternative
*
* Examples and documentation at: http://fancybox.net
*
* Copyright (c) 2008 - 2010 Janis Skarnelis
* That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
*
* Version: 1.3.4 (11/11/2010)
* Requires: jQuery v1.3+
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
followed by a bunch of css. So I believe it's there.
So ... anyone have anything to try?
If you are using:
<a class="single_image" ....
then your script should be:
$(document).ready(function(){
$("a.single_image").fancybox({'type': 'image'});
});
but if with rails you are setting a different class ("fancybox" for instance) like:
<% #image_files.each do |image_file_name| %>
<%=link_to(image_tag image_file_name, :class=>"fancybox", :size => "200x200") %>
<% end %>
then the js script should match the selector's class:
$(document).ready(function(){
$("a.fancybox").fancybox({'type': 'image'});
});
I'll answer your aside first: "why is the new asset pipeline better than just putting a javascript file in a known directory and using a javascipt_include_tag?"
The Pipeline is parts of the Rails "fast by default" strategy. The old way of doing things - linking each file - resulted in multiple downloads and was slower than having just one file. The old way did not compress (minify) the content of the file, adding to download size (and page slowness).
The Pipeline combines content minification and compression with file concatenation to give you a single file for javascript and CSS for use in production. Added to this, the pipeline uses fingerprints in the filenames that are served. Have a read of the Rails asset pipeline guide, as this has a good explanation of why fingerprinting is useful.
Now on to your specific issue.
Fancybox works by attaching a click handler to the image links, and this drives the popup behaviour.
If you click on an image and it shows you full size image, this means that fancybox has not attached itself to the link.
I can see in your code that you are using the class "single_image" on your links. The Javascript snippet you have posted is expecting the class "fancybox". (as JFK has the other answer)
You'll need to change them to match.
The javascript snippet itself should be in the application.js file.
To get the CSS working for this you'll also need to include the application CSS into your layout:
stylesheet_link_tag "application", :media => "all"
javascript_include_tag "application"

Resources