lookup_context.rb 7.3 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] }
J
José Valim 已提交
55
    register_detail(:handlers){ Template::Handlers.extensions }
56

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

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

      def self.get(details)
A
Aaron Patterson 已提交
65
        @details_keys[details] ||= new
66 67
      end

68 69 70 71
      def self.clear
        @details_keys.clear
      end

J
José Valim 已提交
72 73
      def initialize
        @hash = object_hash
74 75 76
      end
    end

77 78 79
    # Add caching behavior on top of Details.
    module DetailsCache
      attr_accessor :cache
80

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
      # 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)
98
        @details = @details.dup if @details_key
99
        @details_key = nil
A
Aaron Patterson 已提交
100
        @details[key] = value
101
      end
102 103
    end

104
    # Helpers related to template lookup using the lookup context information.
105
    module ViewPaths
106
      attr_reader :view_paths, :html_fallback_for_js
107

108 109 110
      # Whenever setting view paths, makes a copy so we can manipulate then in
      # instance objects as we wish.
      def view_paths=(paths)
111
        @view_paths = ActionView::PathSet.new(Array(paths))
112
      end
113

114 115
      def find(name, prefixes = [], partial = false, keys = [], options = {})
        @view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
116
      end
117
      alias :find_template :find
118

119 120
      def find_all(name, prefixes = [], partial = false, keys = [], options = {})
        @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
121 122
      end

123 124
      def exists?(name, prefixes = [], partial = false, keys = [], options = {})
        @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
125
      end
126
      alias :template_exists? :exists?
127

J
José Valim 已提交
128
      # Add fallbacks to the view paths. Useful in cases you are rendering a :file.
129 130 131 132 133 134
      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
135
        end
136 137 138
        yield
      ensure
        added_resolvers.times { view_paths.pop }
139
      end
140 141 142

    protected

143
      def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
A
artemave 已提交
144
        name, prefixes = normalize_name(name, prefixes)
145 146 147 148 149 150 151 152 153
        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)]
154 155 156 157 158
      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 已提交
159
      def normalize_name(name, prefixes) #:nodoc:
160
        prefixes = prefixes.presence
161
        parts    = name.to_s.split('/')
162
        parts.shift if parts.first.empty?
163
        name     = parts.pop
A
artemave 已提交
164

165 166 167 168
        return name, prefixes || [""] if parts.empty?

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

        return name, prefixes
171
      end
172 173
    end

174 175 176
    include Accessors
    include DetailsCache
    include ViewPaths
177

178
    def initialize(view_paths, details = {}, prefixes = [])
J
José Valim 已提交
179
      @details, @details_key = {}, nil
180
      @skip_default_locale = false
181 182
      @cache = true
      @prefixes = prefixes
183
      @rendered_format = nil
184

185 186 187
      self.view_paths = view_paths
      initialize_details(details)
    end
188

189 190 191 192
    # Override formats= to expand ["*/*"] values and automatically
    # add :html as fallback to :js.
    def formats=(values)
      if values
193
        values.concat(default_formats) if values.delete "*/*"
194 195 196 197
        if values == [:js]
          values << :html
          @html_fallback_for_js = true
        end
198
      end
199 200
      super(values)
    end
201

202 203 204 205 206
    # Do not use the default locale on template lookup.
    def skip_default_locale!
      @skip_default_locale = true
      self.locale = nil
    end
207

208 209 210 211
    # Override locale to return a symbol instead of array.
    def locale
      @details[:locale].first
    end
212

213 214 215 216 217 218 219
    # 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 已提交
220 221
      end

222
      super(@skip_default_locale ? I18n.locale : default_locale)
223
    end
224

225 226 227 228 229 230 231
    # 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])
232

233 234 235
        begin
          yield
        ensure
236
          _set_detail(:formats, old_formats)
237 238
        end
      end
239 240
    end
  end
A
artemave 已提交
241
end