Module: Ext::Mount::ControllersClassMethods

Defined in:
lib/ext/mount.rb

Instance Method Summary collapse

Instance Method Details

#mount(path, opts = {}) ⇒ Object

Mounts the path given by ‘path’

Options :

* urls : list of accessible
* name : name of the controller, false sets no controller
* listing : set to false if you don't want directory listing.

Option defaults for ‘/var/my_path’ :

* urls : /my_path(|/.*)
* name : MyPath

Renders the view Views#mount_listing if dir listing is enabled.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/ext/mount.rb', line 82

def mount(path, opts={})
  defaults = {
    :name    => File.basename(path).gsub(/(^|_)(.)/){ $2.upcase },
    :url     => "/#{File.basename(path)}",
    :listing => true
  } 
  opts = defaults.merge(opts)

  urls = ["#{opts[:url].sub(/\/+$/,'')}(|/.*)"]

  klass = Class.new() do
    meta_def(:urls) { urls }
    meta_def(:path) { path }
    meta_def(:listing?) { opts[:listing] }
  end
  klass.class_eval do
    def get(file='') # :nodoc:
      @private_path = File.join(self.class.path, file)
      @rel_path = file
      if File.directory?(@private_path)
        if self.class.listing?
          @public_path = @env.PATH_INFO.sub /\/$/, ''
          @parent_path = @public_path.sub(/[^\/]*$/,'')
          @files = Dir[File.join(@private_path, '*')].map{|f| File.basename(f)}
          class_short = self.class.name.gsub(/^.*::/,'').downcase

          view_name = "#{class_short}_listing"
          if app::Views.method_defined?(view_name)
            render view_name
          else
            render(:mount_listing)
          end
        else
          # TODO : Look if that controller exists
          forward(self::Unauthorized)
        end
      else
        sendfile(@private_path)
      end
    end
  end

  const_set(opts[:name], klass)
  self::r << klass # register route

  if $DBG
    puts "** mounted #{klass} => #{path}"
  end

  klass
end