Checking CSS within a rails controller or in plain ruby? - ruby-on-rails

I need to take a database text field and parse it for
duplication and garbage
malice
whitelisted selectors
compress and output as a css file
Since there might be a rails way I'm unaware or something ready made I'm asking before I waste time trying to reinvent a wheel. My searching revealed nothing, mostly in rails seems aimed at view level, and css seems to be an unattended niche in this area (plenty of html though).
I'm aware of the sanitize gem (doesn't do css immediately, yet another thing I'd need to map out and code) and the built in rails stuff (not a lot of tutorial, aimed mostly at the view level). I need a gem, lib, module or something similar that I can work with in a controller or queue.
EDIT:
Without getting too deep into the specifics of the project: administrative users can add css for their portions of the site. As part of the flow I'm going to save the raw css and then process and save the processed css. The db stuff is archival mostly, the css file is output immediately. Because there is few places to add modified css and only admins have access to the css, it sort of works but I'm looking to make it more robust in the future where admins who may not be as conversant with the security needs or not as css aware can operate.
The most basic example is that it just a text field on an admin page. The admin cuts and pastes css there, submits, and the application turns it into a css file that gets included with the designated pages, which works because the current admins know the application, the css of the application, and what they can and cannot change. The goal is to make this more robust for future admins who might not be as savvy.

To simply sanitize CSS, you can use the SanitizeHelper built into Rails: http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-sanitize_css
Have you looked at Sass? It has all of the parsing logic built in, for a superset of CSS. You could add a feature (Sass support) and save yourself the need to parse/validate the CSS all in one go.
You can generate output CSS from Sass (or just plain CSS, since Sass [with the SCSS syntax] is a fully-backward-compatible superset of CSS) like this:
output_css = Sass::Engine.new(sass_content, :syntax => :scss).render
There are a bunch of options that you'll probably want to look into at http://sass-lang.com/
Another option is Less. The new Twitter Bootstrap framework uses Less, and Rails 3.1 uses Sass. The biggest difference is that the official Less parser/compiler is built in JavaScript, so you could actually validate and compile in the user's browser while they work and show them any errors before they save. Of course then you need to run a JavaScript engine (e.g. V8) in your Rails application if you want to use Less to validate the incoming CSS still.

Related

What are the reasons to use erb integration for webpacker in Rails 6?

I have surfed a couple of hours through the web but couldn't find any articles/walkthroughs/comparisons touching erb integration of webpacker. I've found 1 question, unfortunately, the author haven't read docs attentively and the answer was right there, so - no any additional info there.
I have seen plenty of articles about vue and react, but nobody says a word about erb. However, it's quite clear why using react/vue/else similiar, it is not with erb.
The theme is quite vast and I expect a little hate towards me, so I'd ask two related questions (but if you have something to tell more about it - that's appreciated).
As I understand - it's vanilla (plain) js (maybe with a flavour of jQuery) caring just about dom and styling, with all the preprocessing made by rails. If it is so why not just continue using sprockets?
And what are the reasons to choose it instead of some react/vue/else framework?
You may use both : a vanilla JS framework (React, Vue ...) and some erb files. I find it interesting to setup my constant and other configuration variables within a .js.erb file that is generated by my Rails app when building the js app.
Things I like to put in this erb files :
schemas of my api, generated by my serializers
constants, like enum
values to be used in forms
To generalize, you can put anything owned by the backend that will not change at run time
this save you a couple API calls to retrieve this data. However, I tend to stop doing this as your JS app and Rails become tightly coupled and you can't use the sources of your JS app outside the Rails app

Embedding Handlebars templates in Backbone views, or possibly vice versa

I'm working on a Grails app with client-side Backbone views that use Handlebars templates. Right now the views in .js files and the templates are in .html files. The .js files are rolled up together into an application bundle file, which can be compressed, cached, etc. The .html files are inlined using the Include plugin and show up directly in the generated HTML source.
This has a couple of annoyances.
for ease of development, I'd like to get these into a single file, so you don't have to find and open two files every time you want to work on a view, and you don't risk loading the .js but not including the .html or vice versa.
I'd like the templates themselves to have the benefit of compression, caching and so on rather than being repeated every time we generate HTML.
I can see some ways to do (1) -- e.g., wrap the .js in a <script> tag and embed it directly in the .html -- but they lose the benefits of (2). I can see some ways to do (2) -- e.g., precompile the Handlebars templates with the Handlebars-Resources plugin and treat them like any other Javascript -- but that doesn't get you to (1).
I guess ideally I'd have the HTML embedded in the .js files. But I don't want inline strings; I want it to be clear to my IDE that the HTML is HTML, with all the completion and error-checking benefits that entails. Is there a clean way to do that? Or another alternative I haven't thought of?
From a code maintainability point of view embedding your view code into <script> tags would be a nightmare, and I doubt it would even work. Embedding HTML in a code file is even more horrifying. Even if you could hack together some setup with grep and duct tape, I'm pretty sure there's no IDE that would understand it and give you the syntax hightlighting you want.
Just arrange your IDE windows/tabs next to each other and don't overthink it.
Use the Handlebars precompilation support. It's great.

If I wanted to create a ruby/rails gem to manage CSS class precedence, where would I start?

This is what I want my gem to do...once included in a Rails gem file, it will allow the developer to specify which stylesheet is the main, and which is a 'secondary'. The idea being, that all the styles in the first stylesheet take precedence over all the others - but when a style does not exist in the main, it uses the ones in secondary.
For instance, if there is body in main.css and in secondary.css, it always uses the style from main.css. But if there is alert-message in secondary.css, but not in main, the developer can use alert-message, without any fear of conflicts.
The idea basically is to allow you to leverage existing frameworks or minified stylesheets that might have classes that clash with your main.css without having to worry that your entire site/app will be messed up.
It would be awesome if I could get a general overview of the entire Rails/Ruby gem creating process - as this would be my first. Then maybe some discussions about how I might go about solving this particular problem (from a high-level is fine).
I imagine that it would require a lot of work. You'd have to extend (or write your own) CSS parser. Or come up with another way of specifying which classes are "main".
I think, the solution is much less complicated. Simply include your "main" stylesheet after all "secondaries". That'll overwrite the classes, if there are conflicts.

Sharing colors between SASS files and Rails erb templates

I'm working on an email newsletter using ActionMailer that's associated to our Rails 3.0.7 application. So against all my instincts, I'm using inline styles like mad since that seems to be the only way to do things in html email. I'd also like to keep the color scheme consistent with the website in a DRY fashion.
Is there any way to share SASS color variables between a Rails application and its SCSS files for use in inline styling?
The only way I'm aware you can do this is to add .erb onto your sass files so that they're processed by Rails, then you can use application level constants:
<%= APP_CONFIG[:yourkey] %>
Similar question / more reading
Coding emails is such a heinous task that I try to turn off all the higher thinking regions of my brain that worry about good programming principles every time I have to do it. Unless email is the central part of this project I'd resist letting the constraints there affect the rest of your application design.
Best solution I've found so far is the premailer gem: https://github.com/alexdunae/premailer/
Post-processing your HTML with premailer inlines all the CSS defined in a separate stylesheet, letting you specify whatever you want in a SASS or CSS file.

Ways to organise CSS in Rails project

I would like to know what are the best ways to organise CSS code in Rails project?
I'm interested in how you do it and why.
If you would like to break up your css into multiple files during development you can add cache => true to stylesheet_link_tag and rails will automatically concatenate them into a single file in production. This also works for javascript_include_tag.
http://guides.rubyonrails.org/layouts_and_rendering.html#linking-to-javascript-files-with-javascript_include_tag
Generally, you should not have the client download a massive amount of CSS snippets, but pack them into a single file on the server to avoid rendering latencies. So you have the tradeoff of having functionality divided up into multiple files put wanting to send only one file to the client.
You could use SASS to have each piece of code inside a single include file and just include all of them together. This gives you the added advantage of mixins (kind of like macros) and variables among other awesome things.
Another possibility would be to use plain CSS and use something like Jammit to pack the stuff up to send to the client.
Regarding actual setups, I tend to have one file resetting the styles to a known default, a file for the basic layout (columns, default spaces, ...), and one file each for each area of concern for your specific design (headers, buttons, ...)
James and Holger's answers are very good.
Besides organizing CSS in my projects, I also had to change colour schemes a couple of times..
Trying to do consistent changes throughout many CSS files can be pretty painful (results may vary).
I ended up extending the Rails start-up procedure a little, to include a custom module "site_settings.rb"
through which I can define variable for colors and other CSS attributes, which I can then use throughout my CSS input files.
Whenever Rails starts up, and one of the input files has changed, it auto-generates the CSS files.
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
Since Rails 3.1 is out and sprockets replaced Jammit, here an excerpt form the Rails guides concerning the asset organization:
Asset Organization
Assets can be placed inside an application in one of three locations: app/assets, lib/assets or vendor/assets.
app/assets is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
lib/assets is for your own libraries’ code that doesn’t really fit into the scope of the application or those libraries which are shared across applications.
vendor/assets is for assets that are owned by outside entities, such as code for JavaScript plugins.

Resources