Merge branch 'master' into 2756-eventbus-in-workbench
[arvados.git] / services / api / lib / has_uuid.rb
1 module HasUuid
2
3   def self.included(base)
4     base.extend(ClassMethods)
5     base.before_create :assign_uuid
6     base.before_destroy :destroy_permission_links
7     base.has_many :links_via_head, class_name: 'Link', foreign_key: :head_uuid, primary_key: :uuid, conditions: "not (link_class = 'permission')", dependent: :restrict
8     base.has_many :links_via_tail, class_name: 'Link', foreign_key: :tail_uuid, primary_key: :uuid, conditions: "not (link_class = 'permission')", dependent: :restrict
9   end
10
11   module ClassMethods
12     def uuid_prefix
13       Digest::MD5.hexdigest(self.to_s).to_i(16).to_s(36)[-5..-1]
14     end
15     def generate_uuid
16       [Server::Application.config.uuid_prefix,
17        self.uuid_prefix,
18        rand(2**256).to_s(36)[-15..-1]].
19         join '-'
20     end
21   end
22
23   protected
24
25   def respond_to_uuid?
26     self.respond_to? :uuid
27   end
28
29   def assign_uuid
30     return true if !self.respond_to_uuid?
31     return true if uuid and current_user and current_user.is_admin
32     self.uuid = self.class.generate_uuid
33   end
34
35   def destroy_permission_links
36     Link.destroy_all(['link_class=? and (head_uuid=? or tail_uuid=?)',
37                       'permission', uuid, uuid])
38   end
39 end