Sha256: 174b8e474cf6c5a2874130d00eb29c677db004fbf644d69d220991a193acdc48

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

module Couch
  class Mapper
    MIME_TYPES = {
      ".html" => "text/html",
      ".js" => "text/javascript",
      ".css" => "text/css",
    }

    def initialize(root)
      raise "Root invalid" unless root && File.directory?(root)
      @root = root
    end

    def doc
      map @root
    end

    private

    def map(dirname, hash = {})
      Dir.entries(dirname).each do |file|
        next if file =~ /^\./
        filename = File.join(dirname, file)
        key = file.sub(/\.js$/, '')
        hash[key] = if file == "_attachments"
                      map_attachments(filename)
                    elsif File.directory?(filename)
                      map filename
                    else
                      File.read(filename).strip
                    end
      end
      hash
    end

    def map_attachments(dirname, hash = {}, keys = [])
      Dir.entries(dirname).each do |file|
        next if file =~ /^\./
        filename = File.join(dirname, file)
        base = keys + [file]
        if File.directory?(filename)
          map_attachments filename, hash, base
        else
          hash[base.join('/')] = {
            "content_type" => mime_type(filename),
            "data" => base64(File.read(filename)),
          }
        end
      end
      hash
    end

    # CouchDB needs base64 encodings without spaces
    def base64(data)
      [data].pack("m").gsub(/\s/,'')
    end

    def mime_type(filename)
      ext = File.extname(filename)
      MIME_TYPES[ext] || 'text/plain'
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
couch-0.0.2 lib/couch/mapper.rb