EzDevInfo.com

rack

a modular Ruby webserver interface Rack: a Ruby Webserver Interface

Why is rack response body an array not a string?

a classic hello world example from their doc,

class HelloWorld
  def call(env)
    return [200, {}, ["Hello world!"]]
  end
end

my question is why the third value is [Hello world!"], not "Hello world"? From their doc,

The Body must respond to each and must only yield String values. The Body itself should not be an instance of String, as this will break in Ruby 1.9.

Why body needs to respond to each? and in what case does it matter?


Source: (StackOverflow)

Logging in Sinatra?

I'm having trouble figuring out how to log messages with Sinatra. I'm not looking to log requests, but rather custom messages at certain points in my app. For example, when fetching a URL I would like to log "Fetching #{url}".

Here's what I'd like:

  • The ability to specify log levels (ex: logger.info("Fetching #{url}"))
  • In development and testing environments, the messages would be written to the console.
  • In production, only write out messages matching the current log level.

I'm guessing this can easily be done in config.ru, but I'm not 100% sure which setting I want to enable, and if I have to manually create a Logger object myself (and furthermore, which class of Logger to use: Logger, Rack::Logger, or Rack::CommonLogger).

(I know there are similar questions on StackOverflow, but none seem to directly answer my question. If you can point me to an existing question, I will mark this one as a duplicate).


Source: (StackOverflow)

Advertisements

Where do you put your Rack middleware files and requires?

I'm in the process of refactoring some logic built into a Rails application into middleware, and one annoyance I've run into is a seeming lack of convention for where to put them.

Currently I've settled on app/middleware but I could just as easily move it to vendor/middleware or maybe vendor/plugins/middleware...

The biggest problem is having to require the individual files at the top of config/environment.rb

require "app/middleware/system_message"
require "app/middleware/rack_backstage"

or else I get uninitialized constant errors on the config.middleware.use lines. That could get messy very quickly. I'd rather this was tucked away in an initializer somewhere.

Is there a conventional place to put this stuff?


The specific answer I'm looking for with this bounty is: where can I put the require lines so that they are not cluttering the environment.rb file but still get loaded before the config.middleware.use calls? Everything I have tried leads to uninitialized constant errors.


Update: Now that we're using Rails 3.0, I treat a Rails app like any other Rack app; code files for middleware go in lib (or a gem listed in Gemfile) and are required and loaded in config.ru.


Source: (StackOverflow)

Rack concurrency - rack.multithread, async.callback, or both?

I'm attempting to fully understand the options for concurrent request handling in Rack. I've used async_sinatra to build a long-polling app, and am now experimenting with bare-metal Rack using throw :async and/or Thin's --threaded flag. I am comfortable with the subject, but there are some things I just can't make sense of. (No, I am not mistaking concurrency for parallelism, and yes, I do understand the limitations imposed by the GIL).

Q1. My tests indicate that thin --threaded (i.e. rack.multithread=true) runs requests concurrently in separate threads (I assume using EM), meaning long-running request A will not block request B (IO aside). This means my application does not require any special coding (e.g. callbacks) to achieve concurrency (again, ignoring blocking DB calls, IO, etc.). This is what I believe I have observed - is it correct?

Q2. There is another, more oft discussed means of achieving concurrency, involving EventMachine.defer and throw :async. Strictly speaking, requests are not handled using threads. They are dealt with serially, but pass their heavy lifting and a callback off to EventMachine, which uses async.callback to send a response at a later time. After request A has offloaded its work to EM.defer, request B is begun. Is this correct?

Q3. Assuming the above are more-or-less correct, is there any particular advantage to one method over the other? Obviously --threaded looks like a magic bullet. Are there any downsides? If not, why is everyone talking about async_sinatra / throw :async / async.callback ? Perhaps the former is "I want to make my Rails app a little snappier under heavy load" and the latter is better-suited for apps with many long-running requests? Or perhaps scale is a factor? Just guessing here.

I'm running Thin 1.2.11 on MRI Ruby 1.9.2. (FYI, I have to use the --no-epoll flag, as there's a long-standing, supposedly-resolved-but-not-really problem with EventMachine's use of epoll and Ruby 1.9.2. That's beside the point, but any insight is welcome.)


Source: (StackOverflow)

HTML5 video will not loop

I have a video as a background to a web page, and I am trying to get it to loop. Here is the code:

<video autoplay='true' loop='true' muted='true'>
  <source src='/admin/wallpapers/linked/4ebc66e899727777b400003c' type='video/mp4'></source>
</video>

Even though I have told the video to loop, it does not. I also tried to get it to loop with the onended attribute (as per this Mozilla support thread, I also tried that bit of jQuery). Nothing has worked so far. Is it an issue with Chrome, or my code?

Edit:

I checked the Network events and HEAD of a working copy (http://fhsclock-labs.heroku.com/no-violence) versus the application I'm trying to get working. The difference is the working copy is serving up the video from a static asset on Heroku (via Varnish, apparently), whilst mine is serving from GridFS (MongoDB).

The Network tab of Chrome's Inspector show that in my application, the video is requested three times. One time the Status is "pending", the second is "canceled", and the final one is 200 OK. The working copy only shows two requests, one's Status is pending and the other is 206 Partial Content. However, after the video plays once, that request changes to "Cancelled" and it makes another request for that video. In my application, that does not happen.

As for Type, in my application, two are "undefined" and the other "video/mp4" (which it is supposed to be). In the working app, all of the requests are "video/mp4".

In addition, I'm getting Resource interpreted as Other but transferred with MIME type undefined. warnings in the Console.

I'm not really quite sure where to begin on this. It's my belief that the issue is server-side, as serving the file as static assets works fine. It could be that the server isn't sending the correct content type. It could be an issue with GridFS. I do not know.

At any rate, the source is here. Any insight that you can offer is appreciated.


Source: (StackOverflow)

How to redirect without www using Rails 3 / Rack?

I understand there are a lot of questions that answer this. I'm familiar with .htaccess and nginx.conf methods, but I do not have access to such traditional configuration methods on heroku.

Simone Carletti gave this answer that leverages Rails 2.x Metals, but I'm using Rails 3 and this isn't compatible. Redirect non-www requests to www urls in Rails

Please note:

I'm not looking for a simple before_filter in my ApplicationController. I'd like to accomplish a rewrite similar to Simone's. I believe this is job for the webserver or middleware like Rack at the very least, so I'd like to leave this bit out of the actual app code.

Goal

redirect                to                  status
----------------------------------------------------
www.foo.com             foo.com             301
www.foo.com/whatever    foo.com/whatever    301

Only hosts matching /^www\./ should be redirect. All other requests should be ignored.


Source: (StackOverflow)

Is there an easy way to have pow serve https?

pow is great, but many things in my app assume https, and it would be a pain to go through them all and add "if not dev environment". Is it possible to have pow serve https?


Source: (StackOverflow)

Use different Procfile in development and production

I have a homemade Sinatra application for which I intend to use Heroku to host it.

I use foreman and shotgun in development, with the following Procfile:

web: shotgun config.ru -s thin -o 0.0.0.0 -p $PORT -E $RACK_ENV

It works great with both development and production. But the thing is, I don't want to use shotgun in production since it's too slow.

Can we use separate Procfile configurations for both dev and prod?


Source: (StackOverflow)

Use Rack::CommonLogger in Sinatra

I have a small web-server that I wrote with Sinatra. I want to be able to log messages to a log file. I've read through http://www.sinatrarb.com/api/index.html and www.sinatrarb.com/intro.html, and I see that Rack has something called Rack::CommonLogger, but I can't find any examples of how it can be accessed and used to log messages. My app is simple so I wrote it as a top-level DSL, but I can switch to subclassing it from SinatraBase if that's part of what's required.


Source: (StackOverflow)

How to setup a Sinatra app under Apache with Passenger?

Let's say I have the simplest single-file Sinatra app. The hello world on their homepage will do. I want to run it under Apache with Phusion Passenger, AKA mod_rails.

  • What directory structure do I need?
  • What do I have to put on the vhost conf file?
  • I understand I need a rackup file. What goes in it and why?

Source: (StackOverflow)

How do I access the Rack environment from within Rails?

I have a Rack application that looks like this:

class Foo
  def initialize(app)
    @app = app
  end
  def call(env)
    env["hello"] = "world"
    @app.call(env)
  end
end

After hooking my Rack application into Rails, how do I get access to env["hello"] from within Rails?

Update: Thanks to Gaius for the answer. Rack and Rails let you store things for the duration of the request, or the duration of the session:

# in middleware
def call(env)
  Rack::Request.new(env)["foo"] = "bar"  # sticks around for one request

  env["rack.session"] ||= {}
  env["rack.session"]["hello"] = "world" # sticks around for duration of session
end

# in Rails
def index
  if params["foo"] == "bar"
    ...
  end
  if session["hello"] == "world"
    ...
  end
end

Source: (StackOverflow)

Rack::Request - how do I get all headers?

The title is pretty self-explanatory. Is there any way to get the headers (except for Rack::Request.env[])?


Source: (StackOverflow)

Any way to serve gzip assets from heroku?

I'm wondering if there is any way to get the Rails webserver (thin) to serve the *.gz files the asset pipeline creates. As I understand, those have a higher compression level than that of Rack::Deflater, which only works with serve_static_assets from within the rackup file and not in config.middleware.

A less optimal solution might be to change the default compression level of Zlib which is what Rack::Deflater references. It should only need to gzip once, then it goes to Rack::Cache, then hopefully a CDN.

A second less optimal solution might be a Rack::Rewrite.


Source: (StackOverflow)

Deleting the current session with Rack::Session::Cookie

I feel like I'm missing something obvious here, and I'm hoping that as soon as I post this someone will shame me with the google search link I was missing :-)

enable :sessions

get '/logout' do
  # What goes here to kill the session?
end

Source: (StackOverflow)

How do you configure WEBrick to use SSL in Rails?

Prior to Rails 3, you could modify the script/server file to add in SSL parameters and tell the server command to use the HTTPS version of WEBrick. Now that all of those scripts are gone, does anyone know how to get this to work with Rails 3 or 4?


Source: (StackOverflow)