How to set a content-type for a specific file with Rack? - ruby

I want to have Rack serve a specific file with a specific content type. It's a .htc file and it needs to be served as text/x-component so that IE will recognize it. In apache I would just do
AddType text/x-component .htc
How can I achieve this with Rack? Currently the file is served by Rack::Static, but I didn't find an option to set the content type.

You can update your config/initializers/mime_types.rb like this:
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
Rack::Mime::MIME_TYPES.merge!({
".ogg" => "application/ogg",
".ogx" => "application/ogg",
".ogv" => "video/ogg",
".oga" => "audio/ogg",
".mp4" => "video/mp4",
".m4v" => "video/mp4",
".mp3" => "audio/mpeg",
".m4a" => "audio/mpeg",
".htc" => "text/x-component"
})

Or just to reply to the question, add this in config/initializers/mime_types.rb:
Mime::Type.register "text/x-component", :htc

Related

Ruby Open-URI - specify content type?

I'm trying
io = open(uri, {ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER})
the result is not what I want.
io.content_type
=> "text/html"
Can I specify I want "application/pdf"?
This seems to work:
io = open(uri, "Content-Type" => "application/pdf", ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE)

Post Multipart file upload with json (text) and files (binary) as parts in Ruby

I'm almost done with a multipart file upload but not quite. The API I am using requires two parts: a meta description (Json) and a file (File).
Here some of the Code:
File.open(file_path) do |image|
request = Net::HTTP::Post::Multipart.new(
url.path,
'metadata' => metadata_as_json_string,
'attachment' => UploadIO.new(image, "image/jpeg", "image.jpg")
)
The trouble I am having is with the 'metadata' part (metadata_as_json_string). Without it everything works fine, but the API requires meta information as json. It works if I save the json content in a file and use it as metadata-part. But my content is not coming from a file.
Any ideas how to provide the metadata without previously saving it in a file?
Thank you
I did find a solution myself by using StringIO:
metadata_file = StringIO.new(metadata_as_json_string)
File.open(file_path) do |image|
request = Net::HTTP::Post::Multipart.new(
url.path,
'metadata' => UploadIO.new(metadata_file, "application/json"),
'attachment' => UploadIO.new(image, "image/jpeg", "image.jpg")
)
Anyway thank you for your time

Set Charset to UTF-8 on html pages for Middleman blog site

I have a Middleman blog hosted on Heroku (http://tomgillard.herokuapp.com) and have been trying to optimise it based on google's PageSpeed recommendations. One recommendation is that I provide a character set on the site's HTML pages.
HTML pages contain the html5 <meta charset="utf-8"> in the <head> but this doesn't seem to be enough os I thought I could set it server side.
Here is my config.ru
require 'rack/contrib'
# Modified version of TryStatic, from rack-contrib
# https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/try_static.rb
# Serve static files under a `build` directory:
# - `/` will try to serve your `build/index.html` file
# - `/foo` will try to serve `build/foo` or `build/foo.html` in that order
# - missing files will try to serve build/404.html or a tiny default 404 page
module Rack
class TryStatic
def initialize(app, options)
#app = app
#try = ['', *options.delete(:try)]
#static = ::Rack::Static.new(lambda { [404, {}, []] }, options)
end
def call(env)
orig_path = env['PATH_INFO']
found = nil
#try.each do |path|
resp = #static.call(env.merge!({'PATH_INFO' => orig_path + path}))
break if 404 != resp[0] && found = resp
end
found or #app.call(env.merge!('PATH_INFO' => orig_path))
end
end
end
# Serve GZip files to browsers that support them
use Rack::Deflater
# Custom HTTP Headers
use Rack::ResponseHeaders do |headers|
headers['Charset'] = 'UTF-8'
end
#Custom Cache Expiry
use Rack::StaticCache, :urls => ["/img", "/css", "/js", "/fonts"], :root => "build"
# Attempt to serve static HTML file
use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html', 'index.html', '/index.html']
# Serve 404 messages:
run lambda{ |env|
not_found_page = File.expand_path("../build/404.html", __FILE__)
if File.exist?(not_found_page)
[ 404, { 'Content-Type' => 'text/html', 'Charset' => 'UTF-8' }, [File.read(not_found_page)] ]
else
[ 404, { 'Content-Type' => 'text/html', 'Charset' => 'UTF-8' }, ['404 - page not found'] ]
end
}
I thought I could use Rack::ResponseHeaders from rack-contrib but I don't think I'm using it correctly;
# Custom HTTP Headers
use Rack::ResponseHeaders do |headers|
headers['Charset'] = 'UTF-8'
end
Like I said, I've searched high and low; consulted docs (Rack, heroku), SO questions, blog posts, github, you name it.
Any help with this is much appreciated.
Cheers,
Tom
I had a similar problem and wanted to optimize my site. You just need to manually set your Content-Type header.
Here's my complete config.ru which achieves a 98/100 on Google PageSpeed (it complains about not embedding my css in the page):
# encoding: utf-8
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
require 'rack/contrib'
require File.expand_path("../rack_try_static", __FILE__)
use Rack::ResponseHeaders do |headers|
headers['Content-Type'] = 'text/html; charset=utf-8' if headers['Content-Type'] == 'text/html'
end
use Rack::Deflater
use Rack::StaticCache, urls: ["/images", "/stylesheets", "/javascripts", "/fonts"], root: "build"
use ::Rack::TryStatic,
root: "build",
urls: ["/"],
try: [".html", "index.html", "/index.html"]
run lambda { [404, {"Content-Type" => "text/plain"}, ["File not found!"]] }
You'll also need to add rack-contrib to your Gemfile for Rack::StaticCache:
gem 'rack-contrib'
You'll also want my rack_try_static.
Edit: Note the current implementation of Rack::StaticCache removes Last-Modified and Etag headers and will break on assets ending with a - followed by a number. I have PRs open for both of these (83 and 84).
This no longer applies as I have moved my blog from heroku to github pages. Thanks for looking.

Paperclip - allow only PDF

How can allow to use upload only some kind of files, for example only PDF, Word or Excel files?
I use Paperclip gem.
Use content_type validation, like here:
validates_attachment :avatar, :content_type => { :content_type => "application/pdf" }

Rails3 mailer with image_tag ignoring host

I've got a Rails3 mailer layout that include images.
This ones are used like :
image_tag("emails/top.gif", :width => "700", :height => "10", :alt => "")
As of Rails 2, this images included the host and produced the expected result. However, since Rails3 the config.action_mailer.default_url_options seems to be ignored.
Is there anything I'm missing?
Update
my config/environment/development.rb include:
config.action_mailer.default_url_options = { :host => 'mydomain.tld' }
Needs to use config.action_mailer.asset_host = 'http://mysite.com' in your environment config file
Credits: wmoxam in #rubyonrails

Resources