Method: FilePath#replace_extension

Defined in:
lib/filepath/filepath.rb

#replace_extension(new_ext) ⇒ FilePath #replace_extensionFilePath Also known as: replace_ext, sub_ext

Replaces or removes the file extension.

Overloads:

  • #replace_extension(new_ext) ⇒ FilePath

    Replaces the file extension with the supplied one. If the file has no extension it is added to the file name together with a dot.

    Examples:

    Extension replacement

    
    src_path = "pages/about.markdown".as_path
    html_path = src_path.replace_extension("html")
    html_path.to_s #=> "pages/about.html"
    

    Extension addition

    
    base = "style/main-style".as_path
    sass_style = base.replace_extension("sass")
    sass_style.to_s #=> "style/main-style.sass"
    

    Parameters:

    • the new extension

    Returns:

    • a new path with the replaced extension

  • #replace_extensionFilePath

    Removes the file extension if present.

    The #remove_extension method provides the same functionality but has a more meaningful name.

    Examples:

    
    post_file = "post/welcome.html"
    post_url = post_file.replace_extension(nil)
    post_url.to_s #=> "post/welcome"
    

    Returns:

    • a new path without the extension

See Also:



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/filepath/filepath.rb', line 329

def replace_extension(new_ext) # FIXME: accept block
  orig_filename = filename.to_s

  if !self.extension?
    if new_ext.nil?
      new_filename = orig_filename
    else
      new_filename = orig_filename + '.' + new_ext
    end
  else
    if new_ext.nil?
      pattern = /\.[^.]*?\Z/
      new_filename = orig_filename.sub(pattern, '')
    else
      pattern = Regexp.new('.' + extension + '\\Z')
      new_filename = orig_filename.sub(pattern, '.' + new_ext)
    end
  end

  segs = @segments[0..-2]
  segs << new_filename

  return FilePath.new(segs)
end