Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def self.role_perms(role_name)
if role_name == :anybody
"return true"
else
"user.acts_as_if? '#{role_name}'"
end
end
def self.access_func(method_name, info)
self_clause = ""
evaluator = ""
info.each_pair do |key,value|
case key
when :owner
if value.nil? || value === true
assoc_id = "user_id"
else
assoc_id = value
end
self_clause = "return true if user and user.id == #{assoc_id}"
else
evaluator = role_perms(key)
end
end
class_eval %{
def #{method_name}(user, parent = nil)
#{self_clause}
#{evaluator}
end
}
end
def self.convert_to_role_hash(*role_names)
role_hash = {}
if role_names.last.is_a? Hash
role_hash = role_names.pop
end
role_names.each do |role|
role_hash[role] = true
end
role_hash
end
def self.update_by (*role_names)
role_hash = convert_to_role_hash(*role_names)
access_func(:is_updatable_by, role_hash)
end
def self.delete_by (*role_names)
role_hash = convert_to_role_hash(*role_names)
access_func(:is_deletable_by, role_hash)
end
def self.read_by (role_name)
evaluator = role_perms(role_name)
class_eval %{
def is_readable_by(user, parent = nil)
#{evaluator}
end
def self.is_indexable_by(user, parent = nil)
#{evaluator}
end
}
end
def self.create_by (role_name)
evaluator = role_perms(role_name)
class_eval %{
def self.is_creatable_by(user, object = nil)
#{evaluator}
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment