Class: Role::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/models/role.rb

Overview

The only purpose of this class is to allow developers to do things like: Membership.first.roles << Role.admin Membership.first.roles.delete Role.admin It basically makes the role_ids column act like a Rails ‘has_many through` collection - this includes automatically saving changes when you add or remove from the array.

Instance Method Summary collapse

Constructor Details

#initialize(model, ary) ⇒ Collection

Returns a new instance of Collection.



110
111
112
113
# File 'lib/models/role.rb', line 110

def initialize(model, ary)
  @model = model
  super(ary)
end

Instance Method Details

#<<(role) ⇒ Object



115
116
117
118
119
120
# File 'lib/models/role.rb', line 115

def <<(role)
  return true if include?(role)
  role_ids = @model.role_ids || []
  role_ids << role.id
  @model.update(role_ids: role_ids)
end

#delete(role) ⇒ Object



122
123
124
125
126
127
128
# File 'lib/models/role.rb', line 122

def delete(role)
  return @model.save unless include?(role)
  current_role_ids = @model.role_ids || []
  new_role_ids = current_role_ids - [role.key]
  @model.role_ids = new_role_ids
  @model.save
end