Sha256: 65f96afdf53d0d418de90e1604c4f323600acd929e19acbcf02b8f15c8434ac8

Contents?: true

Size: 998 Bytes

Versions: 1

Compression:

Stored size: 998 Bytes

Contents

module DirModel
  module Export

    attr_reader :source_model, :context

    # @param [Model] source_model object to export to files
    # @param [Hash]  context
    def initialize(source_model, context={})
      @source_model = source_model
      @context      = OpenStruct.new(context)
      @root_path    = Dir.mktmpdir
    end

    def path
      generate unless generated?
      @root_path
    end

    private

    def generated?
      !!@generated
    end

    def generate
      cleanup if generated?

      self.class.files.each do |file_name, options|
        dir_path  = instance_exec(&options[:path])
        file_path = File.join(dir_path, instance_exec(&options[:name]))

        mkdir { File.join(@root_path, dir_path) }

        File.open(File.join(@root_path, file_path), 'wb') {|f| f.write(self.public_send(file_name).read) }
      end
    ensure
      @generated = true
    end

    def cleanup
      FileUtils.remove_entry @root_path
      @generated = false
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dir_model-0.2.0 lib/dir_model/export.rb