Ruby / Rails - escape uri for use in css

In my application, the user uploads an image, which he then places on S3. This image is then used as the background for the div using the following style

div#id { background: url('<%= creative.url %>') no-repeat;} 

The creative url looks something like this:

http://myhost.s3-website-us-east-1.amazonaws.com/27/display/608-(rec'd_021014)_user_image.jpg?1392767029

As above, the problem is that creative.url may contain special characters (quotation marks, parens, etc.), and according to http://www.w3.org/TR/CSS2/syndata.html#value- def-uri , it must escape.

I hope there will be a handy ruby ​​/ rails function that can take care of this for me.

If not, then I probably will need to replace some kind of regular expression - what will it look like?

Update:

People suggested using the URI encoding functions - I tried it, but the url string is used directly in the ERB template, so it encodes everything that does not work in the css url function, that is, I would kind of (from above):

div#id {background: url('http%3A%2F%2Fmyhost.s3-website-us-east-1.amazonaws.com%2F27%2Fdisplay%2F608-(rec%27d_021014)_user_image.jpg%3F1392767029') no-repeat;}

+6
source share
4 answers

You can try:

URI(url) or URI.encode(url) or URI.decode(url) or URI.parse(url)

Case dependent

You may need to download require 'uri' before

0
source

The recommended way is to use url_encode from ERB :: Util

In Rails, there is an alias u for url_encode.

 div#id { background: url('<%=u creative.url %>') no-repeat;} 
0
source

You can use a dump.

 div#id { background: url('<%= creative.url.dump %>') no-repeat;} 
0
source

I don't think Rails has a CSS helper helper, but a JS helper helper would be better than nothing, as it would avoid quotes, closing brackets, and backslashes. There may be some special CSS characters that will not be affected.

You can set the data- attribute for the element in question, and then use the CSS attr function to reference it. That way you can use it in CSS without worrying about it, avoiding it for CSS.

0
source

All Articles