Rails Authentication system with polymorphic models

Uuuhhh… the title alone sounds funky :)

I want to use polymorphic models for my current app in order to represent the different types of users that the app is handling.

The base model is just a user and inside this model all the log in logic is stored and everything that is shared between all my different user types.

Inspired by cancan I wanted something that would be easy to maintain and easy to setup, therefor I decided to build a simple authentication system which I can then use in my app like this:

Visitor.can?(:view, '/secret/stuff')

and here the Visitor inherits from the User like so Visitor < User and the user is representing the database table in this case.

Inside my Visitor all the permissions are stored in a hash like this:

@permissions  = {
      :view => ["^/$", "deals", "deal\/[0-9]+$"]
    }

as you can see each key is the action and the value is an array of regular expressions. And then in the rails console I tested this like so:

["^/$", "deals", "deal\/[0-9]+$"].collect { |r| "/super/secret".match(r).nil? }

where the path (just a string) being tested is “/super/secret” then the above line of code will return:

[true, true, true]

the path “/super/secret” is not in the array of regular expressions representing the resources a visitor can view. But if I change the path to “/deal/42″ the returned array from the one liner would look like:

[true, true, false]

where false actually tells me that the visitor can view any path looking like “/deal/42″

Running your own taggable in Rails isn’t that hard

I’m working on a Rails app where I want to offer the ability to use tags (labels) for categorization, but they have to be polymorphic since I don’t want to have more than one table with tags. Continue reading

Follow

Get every new post delivered to your Inbox.