RolifyCommunity / rolify

Role management library with resource scoping
https://rolifycommunity.github.io/rolify/
MIT License
3.17k stars 404 forks source link

Bypassing the adapter? #265

Open bytheway875 opened 10 years ago

bytheway875 commented 10 years ago

As it stands, each has_role? call queries the db using the kind-of-complicated query in the adapter. In our app internally, because we eager-load roles with User, this is very heavy and seems kind of unnecessary. So we wrote our own has_role? method that more closely resembles the new record implementation of the method and its working really well so far. So I have a couple of questions:

Anyways, I'm not too sure whether this is something that is feasible or necessary or wanted, but its how we've adapted rolify to work internally. If it is a feature we can add, I'm more than willing to work on it!

tinynumbers commented 9 years ago

Could you share your implementation of has_role??

I ask because I've taken the same approach to cut down on what I also see as unnecessary role queries. My implementation is exactly like the new record implementation:

  def has_role?(role_name, resource = nil)
    self.roles.detect { |r| r.name == role_name.to_s && (r.resource == resource || resource.nil?) }.present?
  end

Works for me, but just wanting to make sure I'm not overlooking anything.

jbyers16 commented 9 years ago

We're currently testing adding a role collection present check. So far seems to work for eager and non-eager loaded roles.

def has_role?(role_name, resource = nil)
    if new_record? || self.roles.present?
      role_array = self.roles.detect { |r| r.name.to_s == role_name.to_s && (r.resource == resource || resource.nil?) }
    else
      role_array = self.class.adapter.where(self.roles, name: role_name, resource: resource)
    end

    return false if role_array.nil?
    role_array != []
  end
tinynumbers commented 9 years ago

Thanks @jbyers16

wldcordeiro commented 9 years ago

If you guys find a better solution that works with Mongo we'd love a PR.