aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib/action_view/helpers/sprockets_helper.rb
blob: ab98da9624475dd54d3df7ba6df2e04872b97822 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require 'uri'
require 'action_view/helpers/asset_paths'

module ActionView
  module Helpers
    module SprocketsHelper
      def asset_path(source, default_ext = nil)
        sprockets_asset_paths.compute_public_path(source, 'assets', default_ext, true)
      end

      def sprockets_javascript_include_tag(source, options = {})
        options = {
          'type' => "text/javascript",
          'src'  => asset_path(source, 'js')
        }.merge(options.stringify_keys)

        content_tag 'script', "", options
      end

      def sprockets_stylesheet_link_tag(source, options = {})
        options = {
          'rel'   => "stylesheet",
          'type'  => "text/css",
          'media' => "screen",
          'href'  => asset_path(source, 'css')
        }.merge(options.stringify_keys)

        tag 'link', options
      end

      private

      def sprockets_asset_paths
        @sprockets_asset_paths ||= begin
          config     = self.config if respond_to?(:config)
          controller = self.controller if respond_to?(:controller)
          SprocketsHelper::AssetPaths.new(config, controller)
        end
      end

      class AssetPaths < ActionView::Helpers::AssetPaths #:nodoc:
        def rewrite_asset_path(source, dir)
          if source[0] == ?/
            source
          else
            assets.path(source, performing_caching?, dir)
          end
        end

        def rewrite_extension(source, dir, ext)
          if ext && File.extname(source).empty?
            "#{source}.#{ext}"
          else
            source
          end
        end

        def assets
          Rails.application.assets
        end

        # When included in Sprockets::Context, we need to ask the top-level config as the controller is not available
        def performing_caching?
          @config ?  @config.perform_caching : Rails.application.config.action_controller.perform_caching
        end
      end
    end
  end
end