Class: Command::Subject

Inherits:
Object
  • Object
show all
Defined in:
lib/command-set/subject.rb

Overview

This object represents the subject of a command set. To expose parts of the application to the command set, commands should call subject_methods with the names of methods it expects to use.

Furthermore, Subject maintains the state of the command set, which helps put all of the logic in the Command objects by letting them maintain state in one place

Subjects are very picky about their fields. The motivation here is to fail fast. Commands can’t access fields they don’t declare with DSL::CommandDefinition#subject_methods, and the interpreter will fail fast unless the required fields have been assigned.

Finally, Commands can’t set fields - but the fields are the same for each command, so they can change the fields. For drastic changes, try Array#replace or Hash#replace

Direct Known Subclasses

PermissiveSubject

Defined Under Namespace

Classes: UndefinedField

Constant Summary collapse

Undefined =
UndefinedField.new

Instance Method Summary collapse

Instance Method Details

#get_image(with_fields) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/command-set/subject.rb', line 41

def get_image(with_fields)
  image = SubjectImage.new
  missing_fields = []
  with_fields.each do |field|
    begin 
      field = field.to_s
      value = instance_variable_get("@#{field}")
      image.add_field(field, value)
    rescue NameError
      missing_fields << field
    end
  end
  unless missing_fields.empty? 
    raise CommandException, "Subject is missing fields: #{missing_fields.join(", ")}"
  end
  image
end

#required_fields(*field_names) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/command-set/subject.rb', line 22

def required_fields(*field_names)
  field_names.map! {|name| name.to_s}
  field_names -= instance_variables.map {|var| var.sub(/^@/, "")}
  field_names.each do |field|
	add_accessor(field)
  end
end

#verifyObject



30
31
32
33
34
35
36
37
38
39
# File 'lib/command-set/subject.rb', line 30

def verify
  missing = instance_variables.find_all do |var| 
	UndefinedField === instance_variable_get(var)
  end
  unless missing.empty?
    missing.map! {|m| m.sub(/^@/,"")}
	raise RuntimeError, "Undefined subject field#{missing.length > 1 ? "s" : ""}: #{missing.join(", ")}" 
  end	
  return nil
end