Class: Indulgence::Ability

Inherits:
Object
  • Object
show all
Defined in:
lib/indulgence/ability.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Ability

Returns a new instance of Ability.



6
7
8
9
10
11
12
13
# File 'lib/indulgence/ability.rb', line 6

def initialize(args = {})
  @name = args[:name]
  @compare_single = args[:compare_single]
  @filter_many = args[:filter_many]
  @relationship = args[:relationship]
  @args = args
  valid?
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



4
5
6
# File 'lib/indulgence/ability.rb', line 4

def args
  @args
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/indulgence/ability.rb', line 4

def name
  @name
end

#relationshipObject (readonly)

Returns the value of attribute relationship.



4
5
6
# File 'lib/indulgence/ability.rb', line 4

def relationship
  @relationship
end

Instance Method Details

#==(another_ability) ⇒ Object



15
16
17
18
19
20
# File 'lib/indulgence/ability.rb', line 15

def ==(another_ability)
  [:name, :args].each do |method|
    return false if send(method) != another_ability.send(method)
  end
  return true
end

#compare_single(thing, entity) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/indulgence/ability.rb', line 30

def compare_single(thing, entity)
  return @compare_single.call thing, entity if @compare_single

  identifier = thing.send(relationship)
  if identifier.kind_of?(Array) || identifier.kind_of?(ActiveRecord::Relation)
    identifier.include? entity
  else
    identifier == entity.id || identifier == entity
  end
end

#filter_many(things, entity) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/indulgence/ability.rb', line 41

def filter_many(things, entity)
  return @filter_many.call things, entity if @filter_many

  if things.reflect_on_association(relationship)
    things.joins(relationship).where(entity.class.table_name => {:id => entity.id})
  else
    things.where(relationship => entity.id)
  end
end

#valid?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
# File 'lib/indulgence/ability.rb', line 22

def valid?
  must_be_name
  unless relationship
    must_respond_to_call @compare_single
    must_respond_to_call @filter_many
  end
end