lookup_context.rb 7.1 KB
Newer Older
1
require 'concurrent'
2
require 'active_support/core_ext/module/remove_method'
3
require 'active_support/core_ext/module/attribute_accessors'
4
require 'action_view/template/resolver'
5

6
module ActionView
7 8
  # = Action View Lookup Context
  #
9 10 11 12 13
  # <tt>LookupContext</tt> is the object responsible for holding all information
  # required for looking up templates, i.e. view paths and details.
  # <tt>LookupContext</tt> is also responsible for generating a key, given to
  # view paths, used in the resolver cache lookup. Since this key is generated
  # only once during the request, it speeds up all cache accesses.
14
  class LookupContext #:nodoc:
15
    attr_accessor :prefixes, :rendered_format
G
Guillermo Iguaran 已提交
16

17
    mattr_accessor :fallbacks
18
    @@fallbacks = FallbackFileSystemResolver.instances
19

20
    mattr_accessor :registered_details
J
José Valim 已提交
21
    self.registered_details = []
22

23
    def self.register_detail(name, options = {}, &block)
J
José Valim 已提交
24
      self.registered_details << name
25
      initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
26

27
      Accessors.send :define_method, :"default_#{name}", &block
28 29
      Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
        def #{name}
A
Aaron Patterson 已提交
30
          @details.fetch(:#{name}, [])
31
        end
J
José Valim 已提交
32

33
        def #{name}=(value)
34
          value = value.present? ? Array(value) : default_#{name}
35
          _set_detail(:#{name}, value) if value != @details[:#{name}]
J
José Valim 已提交
36
        end
37 38 39 40 41

        remove_possible_method :initialize_details
        def initialize_details(details)
          #{initialize.join("\n")}
        end
42
      METHOD
43 44
    end

45 46
    # Holds accessors for the registered details.
    module Accessors #:nodoc:
J
José Valim 已提交
47 48
    end

49 50 51 52 53 54 55
    register_detail(:locale) do
      locales = [I18n.locale]
      locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
      locales << I18n.default_locale
      locales.uniq!
      locales
    end
56
    register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css,  :xml, :json] }
Ł
Łukasz Strzałkowski 已提交
57
    register_detail(:variants) { [] }
J
José Valim 已提交
58
    register_detail(:handlers){ Template::Handlers.extensions }
59

60 61
    class DetailsKey #:nodoc:
      alias :eql? :equal?
J
José Valim 已提交
62
      alias :object_hash :hash
63

J
José Valim 已提交
64
      attr_reader :hash
65
      @details_keys = Concurrent::Map.new
66 67

      def self.get(details)
68 69
        if details[:formats]
          details = details.dup
70
          details[:formats] &= Mime::SET.symbols
71
        end
A
Aaron Patterson 已提交
72
        @details_keys[details] ||= new
73 74
      end

75 76 77 78
      def self.clear
        @details_keys.clear
      end

J
José Valim 已提交
79 80
      def initialize
        @hash = object_hash
81 82 83
      end
    end

84 85 86
    # Add caching behavior on top of Details.
    module DetailsCache
      attr_accessor :cache
87

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      # Calculate the details key. Remove the handlers from calculation to improve performance
      # since the user cannot modify it explicitly.
      def details_key #:nodoc:
        @details_key ||= DetailsKey.get(@details) if @cache
      end

      # Temporary skip passing the details_key forward.
      def disable_cache
        old_value, @cache = @cache, false
        yield
      ensure
        @cache = old_value
      end

    protected

      def _set_detail(key, value)
105
        @details = @details.dup if @details_key
106
        @details_key = nil
A
Aaron Patterson 已提交
107
        @details[key] = value
108
      end
109 110
    end

111
    # Helpers related to template lookup using the lookup context information.
112
    module ViewPaths
113
      attr_reader :view_paths, :html_fallback_for_js
114

115
      # Whenever setting view paths, makes a copy so that we can manipulate them in
116 117
      # instance objects as we wish.
      def view_paths=(paths)
118
        @view_paths = ActionView::PathSet.new(Array(paths))
119
      end
120

121 122
      def find(name, prefixes = [], partial = false, keys = [], options = {})
        @view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
123
      end
124
      alias :find_template :find
125

126 127
      def find_all(name, prefixes = [], partial = false, keys = [], options = {})
        @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
128 129
      end

130
      def exists?(name, prefixes = [], partial = false, keys = [], **options)
131
        @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
132
      end
133
      alias :template_exists? :exists?
134

135 136
      # Adds fallbacks to the view paths. Useful in cases when you are rendering
      # a :file.
137 138 139 140 141 142
      def with_fallbacks
        added_resolvers = 0
        self.class.fallbacks.each do |resolver|
          next if view_paths.include?(resolver)
          view_paths.push(resolver)
          added_resolvers += 1
143
        end
144 145 146
        yield
      ensure
        added_resolvers.times { view_paths.pop }
147
      end
148 149 150

    protected

151
      def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
A
artemave 已提交
152
        name, prefixes = normalize_name(name, prefixes)
153 154 155 156 157 158 159 160
        details, details_key = detail_args_for(details_options)
        [name, prefixes, partial || false, details, details_key, keys]
      end

      # Compute details hash and key according to user options (e.g. passed from #render).
      def detail_args_for(options)
        return @details, details_key if options.empty? # most common path.
        user_details = @details.merge(options)
161 162 163 164 165 166 167 168

        if @cache
          details_key = DetailsKey.get(user_details)
        else
          details_key = nil
        end

        [user_details, details_key]
169 170 171 172 173
      end

      # Support legacy foo.erb names even though we now ignore .erb
      # as well as incorrectly putting part of the path in the template
      # name instead of the prefix.
A
artemave 已提交
174
      def normalize_name(name, prefixes) #:nodoc:
175
        prefixes = prefixes.presence
176
        parts    = name.to_s.split('/'.freeze)
177
        parts.shift if parts.first.empty?
178
        name     = parts.pop
A
artemave 已提交
179

180 181
        return name, prefixes || [""] if parts.empty?

182
        parts    = parts.join('/'.freeze)
183
        prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
184 185

        return name, prefixes
186
      end
187 188
    end

189 190 191
    include Accessors
    include DetailsCache
    include ViewPaths
192

193
    def initialize(view_paths, details = {}, prefixes = [])
J
José Valim 已提交
194
      @details, @details_key = {}, nil
195 196
      @cache = true
      @prefixes = prefixes
197
      @rendered_format = nil
198

199 200 201
      self.view_paths = view_paths
      initialize_details(details)
    end
202

203 204 205 206
    # Override formats= to expand ["*/*"] values and automatically
    # add :html as fallback to :js.
    def formats=(values)
      if values
207
        values.concat(default_formats) if values.delete "*/*".freeze
208 209 210 211
        if values == [:js]
          values << :html
          @html_fallback_for_js = true
        end
212
      end
213 214
      super(values)
    end
215

216 217 218 219
    # Override locale to return a symbol instead of array.
    def locale
      @details[:locale].first
    end
220

221
    # Overload locale= to also set the I18n.locale. If the current I18n.config object responds
222
    # to original_config, it means that it has a copy of the original I18n configuration and it's
223 224 225 226 227
    # acting as proxy, which we need to skip.
    def locale=(value)
      if value
        config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
        config.locale = value
W
wycats 已提交
228 229
      end

230
      super(default_locale)
231
    end
232
  end
A
artemave 已提交
233
end