Skip to content

Instantly share code, notes, and snippets.

@krisleech
Created February 17, 2020 16:08
Show Gist options
  • Save krisleech/c06b538629a7299697ebbce7b4ffad5c to your computer and use it in GitHub Desktop.
Save krisleech/c06b538629a7299697ebbce7b4ffad5c to your computer and use it in GitHub Desktop.
ActionPolicy and SimpleDelegator

Problem: When wrapping a model using SimpleDelegator and passing to authorize! an undefined method _policy_cache_key error occurs.

This is, I think, because ActionPolicy uses refinements to add a method _policy_cache_key to Object.

However SimpleDelegator does not inherit from Object, but maybe BasicObject.

To fix this we need to pass the unwrapped model to authorize! or add the missing method, _policy_cache_key, to our wrapper object.

In controller or mutation:

authorize!(wrapped_model.__getobj__, ...)

or automatically:

def policy_for(record:, **opts)
  record.class.ancestors.include?(SimpleDelegator) ? record.__getobj__ : record
  super(record: record, **opts)
end

Or add to SimpleDelegator wrapper

def _policy_cache_key(*)
  SecureRandom.uuid
end

also see:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment