lookup_context.rb 7.6 KB
Newer Older
1
require 'thread_safe'
2
require 'active_support/core_ext/module/remove_method'
3
require 'active_support/core_ext/module/attribute_accessors'
4

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

15
    mattr_accessor :fallbacks
16
    @@fallbacks = FallbackFileSystemResolver.instances
17

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

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

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

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

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

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

47 48 49 50 51 52 53
    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
54
    register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css,  :xml, :json] }
Ł
Łukasz Strzałkowski 已提交
55
    register_detail(:variants) { [] }
J
José Valim 已提交
56
    register_detail(:handlers){ Template::Handlers.extensions }
57

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

J
José Valim 已提交
62
      attr_reader :hash
63
      @details_keys = ThreadSafe::Cache.new
64 65

      def self.get(details)
66 67 68 69 70 71 72
        if details[:formats]
          details = details.dup
          syms    = Set.new Mime::SET.symbols
          details[:formats] = details[:formats].select { |v|
            syms.include? v
          }
        end
A
Aaron Patterson 已提交
73
        @details_keys[details] ||= new
74 75
      end

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

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

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

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
      # 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)
106
        @details = @details.dup if @details_key
107
        @details_key = nil
A
Aaron Patterson 已提交
108
        @details[key] = value
109
      end
110 111
    end

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

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

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

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

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

J
José Valim 已提交
136
      # Add fallbacks to the view paths. Useful in cases 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 161
        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)
        [user_details, DetailsKey.get(user_details)]
162 163 164 165 166
      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 已提交
167
      def normalize_name(name, prefixes) #:nodoc:
168
        prefixes = prefixes.presence
169
        parts    = name.to_s.split('/')
170
        parts.shift if parts.first.empty?
171
        name     = parts.pop
A
artemave 已提交
172

173 174 175 176
        return name, prefixes || [""] if parts.empty?

        parts    = parts.join('/')
        prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
177 178

        return name, prefixes
179
      end
180 181
    end

182 183 184
    include Accessors
    include DetailsCache
    include ViewPaths
185

186
    def initialize(view_paths, details = {}, prefixes = [])
J
José Valim 已提交
187
      @details, @details_key = {}, nil
188
      @skip_default_locale = false
189 190
      @cache = true
      @prefixes = prefixes
191
      @rendered_format = nil
192

193 194 195
      self.view_paths = view_paths
      initialize_details(details)
    end
196

197 198 199 200
    # Override formats= to expand ["*/*"] values and automatically
    # add :html as fallback to :js.
    def formats=(values)
      if values
201
        values.concat(default_formats) if values.delete "*/*"
202 203 204 205
        if values == [:js]
          values << :html
          @html_fallback_for_js = true
        end
206
      end
207 208
      super(values)
    end
209

210 211 212 213 214
    # Do not use the default locale on template lookup.
    def skip_default_locale!
      @skip_default_locale = true
      self.locale = nil
    end
215

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

221 222 223 224 225 226 227
    # Overload locale= to also set the I18n.locale. If the current I18n.config object responds
    # to original_config, it means that it's has a copy of the original I18n configuration and it's
    # 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(@skip_default_locale ? I18n.locale : default_locale)
231
    end
232

233 234 235 236 237 238 239
    # A method which only uses the first format in the formats array for layout lookup.
    def with_layout_format
      if formats.size == 1
        yield
      else
        old_formats = formats
        _set_detail(:formats, formats[0,1])
240

241 242 243
        begin
          yield
        ensure
244
          _set_detail(:formats, old_formats)
245 246
        end
      end
247 248
    end
  end
A
artemave 已提交
249
end