Sha256: 5409dfff6978eafe081d6aa413047cde7560175f6297cb901703d93ced8e7290

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

module Rwiki::Models
  class Folder < Node

    def initialize(path)
      full_path = File.join(@@working_path, path)
      raise Rwiki::NodeNotFoundError.new("cannot find #{path}") if !File.exist?(full_path) || ! File.directory?(full_path)
      super(path)
    end

    def nodes
      Dir.chdir(working_path) do
        self.class.make_tree(@path)
      end
    end

    def create_sub_folder(name)
      new_folder_path = File.join(@path, name)
      new_folder_full_path = self.class.full_path_for(new_folder_path)
      raise Rwiki::NodeError.new("#{new_folder_path} already exists") if File.exists?(new_folder_full_path)

      FileUtils.mkdir(new_folder_full_path)
      return Folder.new(new_folder_path)
    end

    def create_sub_page(name)
      name = name + '.txt' unless name.end_with?('.txt')
      new_page_path = File.join(@path, name)
      new_page_full_path = self.class.full_path_for(new_page_path)
      raise Rwiki::NodeError.new("#{new_page_path} already exists") if File.exists?(new_page_full_path)

      FileUtils.touch(new_page_full_path)
      return Page.new(new_page_path)
    end

    private

    def self.make_tree(root_path)
      tree_nodes = []

      nodes = Dir.entries(root_path).sort
      nodes.each do |base_name|
        next if base_name.match(/^\./) # skip hidden files

        path = File.join(root_path, base_name)
        tree_node = { :baseName => base_name }

        if File.directory?(path)
          children = make_tree(path)
          tree_nodes << tree_node.merge(:text => base_name, :cls => 'folder', :children => children)
        else
          next unless base_name.match(/#{PAGE_FILE_EXTENSION}$/) # skip non *.txt files

          page_name = base_name.gsub(/#{PAGE_FILE_EXTENSION}$/, '')
          tree_nodes << tree_node.merge(:text => page_name, :cls => 'page', :leaf => true)
        end
      end

      return tree_nodes
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rwiki-0.1.3 lib/rwiki/models/folder.rb