group_child_entity.rb 2.11 KB
Newer Older
1 2 3 4
class GroupChildEntity < Grape::Entity
  include ActionView::Helpers::NumberHelper
  include RequestAwareEntity

5 6
  expose :id, :name, :description, :visibility, :full_name,
         :created_at, :updated_at, :avatar_url
7

8
  expose :type do |instance|
9
    type
10 11
  end

12
  expose :can_edit do |instance|
13 14
    return false unless request.respond_to?(:current_user)

15
    can?(request.current_user, "admin_#{type}", instance)
16 17
  end

18
  expose :edit_path do |instance|
19 20 21 22 23
    # We know `type` will be one either `project` or `group`.
    # The `edit_polymorphic_path` helper would try to call the path helper
    # with a plural: `edit_groups_path(instance)` or `edit_projects_path(instance)`
    # while our methods are `edit_group_path` or `edit_group_path`
    public_send("edit_#{type}_path", instance) # rubocop:disable GitlabSecurity/PublicSend
24 25
  end

26
  expose :relative_path do |instance|
27
    polymorphic_path(instance)
28 29
  end

30
  expose :permission do |instance|
31
    membership&.human_access
32 33 34 35 36 37 38
  end

  # Project only attributes
  expose :star_count,
         if: lambda { |_instance, _options| project? }

  # Group only attributes
39
  expose :children_count, :parent_id, :project_count, :subgroup_count,
40 41
         unless: lambda { |_instance, _options| project? }

42 43
  expose :leave_path, unless: lambda { |_instance, _options| project? } do |instance|
    leave_group_members_path(instance)
44 45
  end

46
  expose :can_leave, unless: lambda { |_instance, _options| project? } do |instance|
47
    if membership
48 49 50 51 52 53
      can?(request.current_user, :destroy_group_member, membership)
    else
      false
    end
  end

54 55
  expose :number_projects_with_delimiter, unless: lambda { |_instance, _options| project? } do |instance|
    number_with_delimiter(instance.project_count)
56 57
  end

58 59
  expose :number_users_with_delimiter, unless: lambda { |_instance, _options| project? } do |instance|
    number_with_delimiter(instance.member_count)
60
  end
61 62 63 64 65 66

  private

  def membership
    return unless request.current_user

67
    @membership ||= request.current_user.members.find_by(source: object)
68
  end
69 70 71 72

  def project?
    object.is_a?(Project)
  end
73 74 75 76

  def type
    object.class.name.downcase
  end
77
end