• Stars
    star
    225
  • Rank 177,187 (Top 4 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 15 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Allow your models to know who the current_user is.

sentient_user

<img src=“https://secure.travis-ci.org/bokmann/sentient_user.png” />

How often have you needed to access the current user in your models? This happens often if you are attempting intelligent logging or if you want the models to control some aspect of their access, etc. This is easy hackery that you can find in many blog entries, but I wanted a nice package for it, for several reasons:

  • There are several different ways this can be accomplished, but only the variation that uses Thread.local is safe for use in thread-safe rails.

  • Even using Thread.local is considered slightly hacky (but better than monkeypatching ActiveRecord::Base)

  • Should fashions change in this area in Rails’ future, I want one place to change it, and to keep my methods working.

  • This concept generally breaks in the console, where there is no controller to set the user. This gem adds a make_current method on the user instance, so you can choose to find a user and execute the current_user method. That could be really useful in rake tasks, for instance.

Usage

  • include SentientUser in your user model

  • include SentientController in your application controller

Assumptions and limitations

  • Your user model is called ‘User’.

  • You have a current_user method available to your controllers

  • You will write your own tests to cover this code. The gem has tests, but its up to you to make sure you use this ability wisely.

If those assumptions don’t work for you, feel free to unpack and hack. It’s simple enough code to change. I purposefully didn’t want to complicate it with an initializer, several config options, etc. as all that would blur this delightfully simple piece of code.

Recent Changes

This gem has been remarkably stable for many years and many iterations of rails. The recent deprecation of before_filter in favor of before_action is making me update it.

  • 0.4.0 - for use on Rails 5 and beyond.

  • 0.3.3 - for versions prior to rails 5.

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it unintentionally in a future version.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but please bump the version in a commit by itself which I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Copyright © 2009-2016 bokmann. See LICENSE for details.