Sha256: f6c9025ee31c77ec4c379e6260ed345d82f90efe4936e05ccc6c8fec9f681577

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

module Couch
  class Mapper
    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" => "text/plain",
            "data" => base64(File.read(filename)),
          }
        end
      end
      hash
    end

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

Version data entries

1 entries across 1 versions & 1 rubygems

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