Last active
September 30, 2015 13:48
-
-
Save shipiev/d50345824f258e27628f to your computer and use it in GitHub Desktop.
has_policy initialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HasPolicy | |
extend ActiveSupport::Concerns | |
included do | |
delegate :default_policy, to: :'self.class', allow_nil: true, prefix: false | |
end | |
module ClassMethods | |
def has_policy(policy_name = nil) | |
@@policy_class = | |
if policy_name.is_a?(Class) | |
policy_name | |
elsif policy_name.is_a?(Symbol) || policy_name.is_a?(String) | |
policy_name.constantize | |
else | |
default_policy | |
end | |
include HasPolicy::PolicyMethods | |
end | |
def default_policy | |
if @@default_policy | |
@@default_policy | |
else | |
@@default_policy = "#{self.class.name}Policy".constantize | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HasPolicy::Methods | |
extend ActiveSupport::Concerns | |
include do | |
end | |
def policy(policy_name = nil) | |
if policy_name | |
if policy_name.is_a? Class | |
policy_name | |
elsif policy_name.is_a?(Simbol) || policy_name.is_a?(String) | |
name = policy_name.to_s.camelize | |
if name[/Policy$/] | |
name | |
else | |
"#{name}Policy" | |
end.constantize | |
else | |
default_policy | |
end | |
else | |
@@policy_class || default_policy | |
end.new(current_user, self) # for pundit gem | |
end | |
private | |
def current_user | |
User.respond_to?(:current) && User.current # It work for Redmine only | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment