Get SASS from database (compile passed data instea

2020-02-16 03:33发布

问题:

Is there any way to make SASS compile data passed from database? I can use DBI + ODBC to get data from MSSQL Server 2008, but how do I make SASS compile passed data instead of file?

Didn't find anything useful, and changing sass core files doesn't sound like a best idea... Especially considering zero Ruby knowledge.

回答1:

I ended up using this chunk of code. Totally not elegant, but I hope it will help someone with pervertish needs.

sql.rb in sass gem dir:

require 'dbi'
require 'sass'
require config with database credentials

if File.exist?(config)
    require config

    SQL_OPTIONS = {
        :style => :nested,
        :load_paths => ['.'],
        :cache => true,
        :cache_location => './.sass-cache',
        :syntax => :scss,
        :filesystem_importer => Sass::Importers::Filesystem,
        :css_location => "./public/stylesheets",
        :always_update => true,
        :template_location => [["scss", "css"]]
    }.freeze

    db = DBI.connect('dbi:ODBC:driver={SQL Server};server=' + $db_host, $db_user, $db_pass)

    db.select_all('SELECT name, scope, content FROM ' + $db_name + '.dbo.scss') do | row |
        File.open(Dir.pwd + '/css/' + row['name'] + '.css', 'w') do |css|  
            css.puts Sass::Engine.new(row['content'], SQL_OPTIONS).render
            puts '  overwrite css/' + row['name'] + '.css [db]'
        end
    end
else
    puts 'ignore database stylesheets, config_ruby doesn\'t exist'
end

In lib/sass/engine.rb I included this file at the end:

require File.expand_path(File.dirname(__FILE__) + '../../../sql')

It requires additional dbi and dbd-odbc gems and affects sass --update as well as --watch.

Hope this helps someone.