Class: Humanoid::Scope

Inherits:
Object show all
Defined in:
lib/humanoid/scope.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, conditions, &block) ⇒ Scope

Create the new Scope. If a block is passed in, this Scope will extend the block.

Options:

parent: The class the scope belongs to, or a parent Scope. conditions: A Hash of conditions.

Example:

Humanoid::Scope.new(Person, { :title => "Sir" }) do
  def knighted?
    title == "Sir"
  end
end


38
39
40
41
# File 'lib/humanoid/scope.rb', line 38

def initialize(parent, conditions, &block)
  @parent, @conditions = parent, conditions
  extend Module.new(&block) if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Chaining is supported through method_missing. If a scope is already defined with the method name the call will be passed there, otherwise it will be passed to the target or parent.



52
53
54
55
56
57
58
59
60
# File 'lib/humanoid/scope.rb', line 52

def method_missing(name, *args, &block)
  if scopes.include?(name)
    scopes[name].call(self, *args)
  elsif klass
    target.send(name, *args, &block)
  else
    @parent.fuse(@conditions); @parent.send(name, *args, &block)
  end
end

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



7
8
9
# File 'lib/humanoid/scope.rb', line 7

def conditions
  @conditions
end

#parentObject (readonly)

Returns the value of attribute parent.



7
8
9
# File 'lib/humanoid/scope.rb', line 7

def parent
  @parent
end

Instance Method Details

#==(other) ⇒ Object

If the other is a scope then compare the parent and conditions, otherwise if its enumerable collect and compare.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/humanoid/scope.rb', line 11

def ==(other)
  case other
  when Scope
    @parent == other.parent && @conditions == other.conditions
  when Enumerable
    @collection ||= entries
    return (@collection == other)
  else
    return false
  end
end

#klassObject

Return the class for the Scope. This will be the parent if the parent is a class, otherwise will be nil.



45
46
47
# File 'lib/humanoid/scope.rb', line 45

def klass
  @klass ||= @parent unless @parent.is_a?(Scope)
end

#respond_to?(name) ⇒ Boolean

The Scope must respond like a Criteria object. If this is a parent criteria delegate to the target, otherwise bubble up to the parent.

Returns:



64
65
66
# File 'lib/humanoid/scope.rb', line 64

def respond_to?(name)
  super || (klass ? target.respond_to?(name) : @parent.respond_to?(name))
end

#targetObject

Returns the target criteria if it has already been set or creates a new criteria from the parent class.



70
71
72
# File 'lib/humanoid/scope.rb', line 70

def target
  @target ||= klass.criteria.fuse(@conditions)
end