在rails应用程序中处理动态css的最佳方法

Chr*_*ger 18 css ruby-on-rails

我正在研究在rails应用程序中处理动态css的问题.在应用程序中,个人用户和/或用户组可以通过CSS实现自定义外观.没有任何固定数量的"外观"或css文件,数量将随着用户和组数量的增长而增长,并且用户通过应用程序的管理界面定义外观.在整个典型的一天中,将提供数千(不是数万)不同的css变体.该应用程序将预先构建的css存储在mongodb中,因此它不必为每个请求支付构建css的代价,问题更多的是如何提供这个动态css内容的最佳方式.我已经看过其他问题,如[这一个] [1],说使用erb或sass,但其中一些答案已经过了几年,所以我想确保Rails 3没有更好的答案.

edg*_*ner 38

您可以将CSS文件视为资源,将它们存储在数据库中,并使用页面缓存为它们提供服务,这样您只需在修改CSS时点击一次 db .所有后来的请求都将由Web服务器直接从缓存中提供,而不会触及您的应用程序或数据库.

# stylesheet.rb
class Stylesheet < ActiveRecord::Base
  validates_presence_of :contents
end

# stylesheets_controller.rb
class StylesheetsController < ApplicationController
  caches_page :show # magic happens here

  def show
    @stylesheet = Stylesheet.find(params[:id])
    respond_to do |format|
      format.html # regular ERB template
      format.css { render :text => @stylesheet.contents, :content_type => "text/css" }
    end
  end
  # the rest is your typical RESTful controller, 
  # just remember to expire the cache when the stylesheet changes
end

# routes.rb
resources :stylesheets

# layouts/application.html.erb
…
<link href="<%= stylesheet_path(@current_user.stylesheet) %>" rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)


Dav*_*ulc 1

这可能会给您一些想法:Multiple robots.txt for subdomains in Rails