Class: FloorManager::Employee::DSL

Inherits:
BlankSlate
  • Object
show all
Defined in:
lib/floor_manager/employee/dsl.rb

Defined Under Namespace

Classes: AssocProxy

Instance Method Summary collapse

Constructor Details

#initialize(employee, filter = :none, &block) ⇒ DSL

Returns a new instance of DSL.



30
31
32
33
34
35
# File 'lib/floor_manager/employee/dsl.rb', line 30

def initialize(employee, filter=:none, &block)
  @employee = employee
  @filter = filter
  
  instance_eval(&block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

This method missing handles several magic incantations:

a) Setting an attribute to a value that is given:

name 'john'

b) Setting an attribute to a value that is returned from a block:

  name { |obj, floor| rand()>0.5 ? 'John' : 'Peter' }

Note that the first argument is the +obj+ under construction (your 
model instance) and the second argument is the floor the model is 
being constructed in. This is useful for retrieving other objects that
live in the same floor.

c) Access to the association magic:

  spouse.set :linda
  friends.append :frank

Please see +AssocProxy+ for further explanation on this.


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/floor_manager/employee/dsl.rb', line 65

def method_missing(sym, *args, &block)
  if args.size == 1
    # Immediate attribute
    value = args.first
    _add_attribute AttributeAction::Immediate.new(sym, value)
  elsif block
    # Lazy attribute
    _add_attribute AttributeAction::Block.new(sym, block)
  elsif args.empty?
    # Maybe: #set / #append proxy?
    AssocProxy.new(@employee, sym, self)
  else
    super
  end
end

Instance Method Details

#_add_attribute(action) ⇒ Object



81
82
83
# File 'lib/floor_manager/employee/dsl.rb', line 81

def _add_attribute(action)
  @employee.add_attribute @filter, action
end

#after_create(&block) ⇒ Object

Register actions to be taken if the object gets saved (floor#create)



39
40
41
# File 'lib/floor_manager/employee/dsl.rb', line 39

def after_create(&block)
  DSL.new(@employee, :after_create, &block)
end