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
      def remove_constant(const, base = nil)
        parts = const.to_s.split("::")
        base ||= parts.size == 1 ? Object : parts[0..-2].join("::").to_const
        object = parts[-1].intern
        puts "Removing #{const} -- #{object} from #{base}"
        base.send(:remove_const, object)
      end

      def reload
        return unless @@merb_opts[:reloader] == true
        # First we collect all files in the project (this will also grab newly added files)
        project_files = MERB_PATHS.map { |path| Dir[MERB_ROOT + path] }.flatten.uniq
        project_mtime = max_mtime project_files # Latest changed time of all project files

        return unless @mtime < project_mtime   # Only continue if a file has changed

        project_files.each do |file|
          if max_mtime(file.to_a) >= @mtime
            # If the file has changed or been added since the last project reload time
            # remove any cannonical constants, based on what type of project file it is
            constant = file =~ /\/(controllers|models|mailers|helpers|parts)\/(.*).rb/ ? $2.to_const_string : nil

            remove_constant($2.to_const_string, ($1 == "helpers") ? Merb : nil)

            load file and puts "loaded file: #{file}"
          end
        end        

        @mtime = project_mtime # As the last action, update the current @mtime
      end