Posts tagged Ruby

May 09th, 2011

Stop Rails trying to parse the POST / PUT request body

Written by Dave BarkerTopics: Rails, Ruby, Howto

Rails 3 has a nice feature where it will parse the body of PUT and POST requests depending on the Content-type given. So for example if I POST XML to Rails it will all be decoded for me and put into the params hash.

Well it's a nice feature until you try to switch it off, it's a nightmare to disable! I managed it in the end, here's what I did.

Created a piece of 'rack middleware' that overwrites the Content-Type for given paths:

# lib/no_parse.rb
class NoParse
  def initialize(app, options={})
    @app = app
    @urls = options[:urls]
  end

  def call(env)
    env['CONTENT_TYPE'] = 'text/plain' if @urls.include? env['PATH_INFO']
    @app.call(env)
  end
end

Included it:

#config/application.rb
require_relative '../lib/no_parse'

Added it into the 'stack':

#config/initializers/no_parse.rb

# (Change the :urls to specify which paths use NoParse.)
Rails.configuration.middleware.insert_before('ActionDispatch::ParamsParser',
                                             'NoParse', :urls => ['/example-path'])

Make sure you restart rails and you should be good to go. If it's not working make sure the rake middleware command is listing the NoParse class above ActionDispatch::ParamsParser.

Cheers, Dave.

January 26th, 2011

Fixing an autoload 'uninitialized constant' NameError

Written by Dave BarkerTopics: Ruby, Howto

I ran into a spot of bother getting some Ruby code to work, I kept getting a uninitialized constant NameError on the line declaring the very class I've autoloaded the file to declare! I got this problem running Ruby 1.9.2p0

Anyway adding this to the top of the file that autoloaded the file giving the error fixed it for me:

$LOAD_PATH.unshift './'

Cheers, Dave.

January 20th, 2011

Installing RVM on a Mac

Written by Dave BarkerTopics: Ruby, Mac, Howto
Just a quick post, here are the commands I ran to get RVM working on my new Macbook:
sudo mkdir /usr/local/lib
sudo bash < <( curl -L http://bit.ly/rvm-install-system-wide )
sudo dseditgroup -o edit -a YOURUSERNAME -t user rvm
echo '[[ -s "/usr/local/lib/rvm" ]] && . "/usr/local/lib/rvm"' >> ~/.bash_profile
source ~/.bash_profile
rvm install 1.9.2
rvm --default use 1.9.2
rvm 1.9.2
ruby --version