environment.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. require 'sprockets/base'
  2. require 'sprockets/charset_normalizer'
  3. require 'sprockets/context'
  4. require 'sprockets/directive_processor'
  5. require 'sprockets/index'
  6. require 'sprockets/safety_colons'
  7. require 'hike'
  8. require 'logger'
  9. require 'pathname'
  10. require 'tilt'
  11. module Sprockets
  12. class Environment < Base
  13. # `Environment` should initialized with your application's root
  14. # directory. This should be the same as your Rails or Rack root.
  15. #
  16. # env = Environment.new(Rails.root)
  17. #
  18. def initialize(root = ".")
  19. @trail = Hike::Trail.new(root)
  20. self.logger = Logger.new($stderr)
  21. self.logger.level = Logger::FATAL
  22. # Create a safe `Context` subclass to mutate
  23. @context_class = Class.new(Context)
  24. # Set MD5 as the default digest
  25. require 'digest/md5'
  26. @digest_class = ::Digest::MD5
  27. @version = ''
  28. @mime_types = {}
  29. @engines = Sprockets.engines
  30. @preprocessors = Hash.new { |h, k| h[k] = [] }
  31. @postprocessors = Hash.new { |h, k| h[k] = [] }
  32. @bundle_processors = Hash.new { |h, k| h[k] = [] }
  33. @engines.each do |ext, klass|
  34. add_engine_to_trail(ext, klass)
  35. end
  36. register_mime_type 'text/css', '.css'
  37. register_mime_type 'application/javascript', '.js'
  38. register_preprocessor 'text/css', DirectiveProcessor
  39. register_preprocessor 'application/javascript', DirectiveProcessor
  40. register_postprocessor 'application/javascript', SafetyColons
  41. register_bundle_processor 'text/css', CharsetNormalizer
  42. expire_index!
  43. yield self if block_given?
  44. end
  45. # Returns a cached version of the environment.
  46. #
  47. # All its file system calls are cached which makes `index` much
  48. # faster. This behavior is ideal in production since the file
  49. # system only changes between deploys.
  50. def index
  51. Index.new(self)
  52. end
  53. # Cache `find_asset` calls
  54. def find_asset(path, options = {})
  55. options[:bundle] = true unless options.key?(:bundle)
  56. # Ensure inmemory cached assets are still fresh on every lookup
  57. if (asset = @assets[cache_key_for(path, options)]) && asset.fresh?(self)
  58. asset
  59. elsif asset = index.find_asset(path, options)
  60. # Cache is pushed upstream by Index#find_asset
  61. asset
  62. end
  63. end
  64. protected
  65. def expire_index!
  66. # Clear digest to be recomputed
  67. @digest = nil
  68. @assets = {}
  69. end
  70. end
  71. end