mongo-ruby-driver/docs/examples/gridfs.rb

45 lines
956 B
Ruby
Raw Permalink Normal View History

2010-01-06 17:21:11 +00:00
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
2010-02-24 20:24:01 +00:00
def assert
raise "Failed!" unless yield
end
2010-01-06 17:21:11 +00:00
2009-02-10 16:51:56 +00:00
require 'mongo'
include Mongo
2009-02-10 16:51:56 +00:00
host = ENV['MONGO_RUBY_DRIVER_HOST'] || 'localhost'
port = ENV['MONGO_RUBY_DRIVER_PORT'] || Connection::DEFAULT_PORT
2009-02-10 16:51:56 +00:00
puts "Connecting to #{host}:#{port}"
db = Connection.new(host, port).db('ruby-mongo-examples')
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
data = "hello, world!"
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
grid = Grid.new(db)
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
# Write a new file. data can be a string or an io object responding to #read.
2010-04-05 21:05:11 +00:00
id = grid.put(data, :filename => 'hello.txt')
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
# Read it and print out the contents
file = grid.get(id)
puts file.read
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
# Delete the file
grid.delete(id)
2009-02-10 16:51:56 +00:00
2010-02-24 20:24:01 +00:00
begin
grid.get(id)
rescue => e
assert {e.class == Mongo::GridError}
end
2009-02-10 16:51:56 +00:00
# Metadata
2010-04-05 21:05:11 +00:00
id = grid.put(data, :filename => 'hello.txt', :content_type => 'text/plain', :metadata => {'name' => 'hello'})
2010-02-24 20:24:01 +00:00
file = grid.get(id)
p file.content_type
p file.metadata.inspect
p file.chunk_size
p file.file_length
2010-04-05 21:05:11 +00:00
p file.filename
2010-02-24 20:24:01 +00:00
p file.data