Class: PageTemplate::FileSource

Inherits:
Source
  • Object
show all
Defined in:
lib/PageTemplate/parser.rb

Overview

FileSource provides access to files within the ‘include_paths’ argument.

It attempts to be secure by not allowing any access outside of The directories detailed within include_paths

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ FileSource

initialize looks for the following in the args Hash:

* include_paths = a list of file paths
* include_path  = a single file path string 
                  (kept for backwards compatibility)


183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/PageTemplate/parser.rb', line 183

def initialize(args = {})
  @args  = args
  if @args['include_paths']
    @paths = @args['include_paths']
  elsif @args['include_path']
    @paths = [ @args['include_path'] ]
  else
    @paths = [Dir.getwd,'/']
  end
  @paths = @paths.compact
  @cache = Hash.new(nil)
  @mtime = Hash.new(0)
end

Instance Attribute Details

#pathsObject (readonly)

Returns the value of attribute paths.



177
178
179
# File 'lib/PageTemplate/parser.rb', line 177

def paths
  @paths
end

Instance Method Details

#cache(name, cmds) ⇒ Object



216
217
218
219
220
# File 'lib/PageTemplate/parser.rb', line 216

def cache(name,cmds)
  fn = get_filename(name)
  @cache[fn] = cmds.dup
  @mtime[fn] = Time.now.to_i
end

#get(name) ⇒ Object

Return the contents of the file name, which must be within the include_paths.



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/PageTemplate/parser.rb', line 199

def get(name)
  fn = get_filename(name)
  begin
    case
	when fn.nil?
	  nil
    when @cache.has_key?(fn) && (@mtime[fn] > File.mtime(fn).to_i)
      cmds = @cache[fn]
	  cmds.clear_cache
	  cmds
    else
      IO.read(fn)
    end
  rescue Exception => er
    return "[ Unable to open file #{fn} because of #{er.message} ]"
  end
end

#get_filename(file) ⇒ Object



221
222
223
224
225
226
227
228
229
# File 'lib/PageTemplate/parser.rb', line 221

def get_filename(file)
  file = file.gsub(/\.\.\//,'') 
  @paths.each do |path|
    fn = File.join(path,file)
    fn.untaint
    return fn if File.exists?(fn)
  end
  return nil
end