Page 105 of 169

Using Rails Sweepers outside controllers

Sweeper outside?

Sometimes we modify some stuff without controllers (for example we publish some stuff via rake task ignited by cron). Unfortunately Rails does not handle it "out of the box", so we need to do it by ourselfs.

BaseSweeper

Let's create a base sweeper class where all the "magic" will happen:

class BaseSweeper < ActionController::Caching::Sweeper

  def after_save(data)
    expire_data(data)
  end

  def after_destroy(data)
    expire_data(data)
  end

  def expire_data
    @controller ||= ActionController::Base.new
  end

end

There's nothing special about this code, except:

@controller ||= ActionController::Base.new

This line will emulate (if needed) controller outside of standard Rails flow. Thanks to this we can sweep stuff whenever we need. Example:

class NewsSweeper < BaseSweeper

  observe News

  def expire_data(data)
      super
      expire_fragment /news_#{data.id}/
  end

end

There's one more thing to do. We need to add sweeper to observers in application.rb file (so our sweeper will react on any change in observed model):
application.rb:

    config.active_record.observers =
      "CommentObserver",
      "JakistamInnyObserver",
      # Sweepery
      "NewsSweeper"

Padrino + Thin Web Server – uninitialized constant Thin::HttpParser (NameError)

New server, new thin, new error while executing:

Padrino/0.9.19 has taken the stage production on 3001
Thin web server (v1.2.8 codename Black Keys)
Maximum connections set to 1024
Listening on localhost:3001, CTRL+C to stop
`initialize': uninitialized constant Thin::HttpParser (NameError)
/thin-1.2.8/lib/thin/connection.rb:35:in `new'
/thin-1.2.8/lib/thin/connection.rb:35:in `post_init'
/eventmachine-0.12.10/lib/em/connection.rb:45:in `new'
/eventmachine-0.12.10/lib/em/connection.rb:36:in `instance_eval'
/eventmachine-0.12.10/lib/em/connection.rb:36:in `new'
/eventmachine-0.12.10/lib/eventmachine.rb:1430:in `event_callback'

Error occurred because there were some old (incompatible) native C extensions after OS upgrade. To fix this just reinstall Thin:

gem uninstall thin
gem install thin

If Thin version changed, you'll also need to run:

bundle install

Copyright © 2025 Closer to Code

Theme by Anders NorenUp ↑