Search code examples
rubyfunctionsassmixins

Sass. Check If Custom Ruby Function Exists


I've written a Sass (SCSS) CSS3 @gradient mixin that also outputs a base64 encoded SVG string for IE9.

This mixin relies upon this custom ruby function be required in the user's Sass "watch" file:

require 'sass'
require 'base64'

module Sass::Script::Functions
    def base64Encode(string)
        assert_type string, :String
        Sass::Script::String.new(Base64.encode64(string.value))
    end
    declare :base64Encode, :args => [:string]
end

which is called like so: base64Encode($svgStr).

However, I'd like to release my mixin library, and don't want to impose that this custom function be required.

For example, AFAIK Web Workbench for VS2012 has no way of including custom functions. If it isn't included, then I don't want to output the base64 rule.

So, is it possible to detect in the mixin whether base64Encode exists as a custom function? Otherwise, you end up with something like:

background-image: url("data:image/svg+xml;base64,base64Encode('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100%\" height=\"100%\" viewBox=\"0 0 1 1\" preserveAspectRatio=\"none\"><linearGradient id=\"g522\" gradientUnits=\"userSpaceOnUse\" x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\"><stop stop-color=\"white\" offset=\"0\" /><stop stop-color=\"whitesmoke\" offset=\"1\" /></linearGradient><rect x=\"0\" y=\"0\" width=\"1\" height=\"1\" fill=\"url(#g522)\" /></svg>')");

instead of

background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRo PSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNl cnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZzUy MiIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIHgxPSIwJSIgeTE9 IjAlIiB4Mj0iMCUiIHkyPSIxMDAlIj48c3RvcCBzdG9wLWNvbG9yPSJ3aGl0 ZSIgb2Zmc2V0PSIwIiAvPjxzdG9wIHN0b3AtY29sb3I9IndoaXRlc21va2Ui IG9mZnNldD0iMSIgLz48L2xpbmVhckdyYWRpZW50PjxyZWN0IHg9IjAiIHk9 IjAiIHdpZHRoPSIxIiBoZWlnaHQ9IjEiIGZpbGw9InVybCgjZzUyMikiIC8+ PC9zdmc+ ");

Or is possible to somehow search inside the returned string to check whether "base64Encode" is there and to ignore it?


Solution

  • This pull request (which has been merged) gives you a 'function-exists' function: https://github.com/nex3/sass/pull/821