Class: JazzModel::Definition

Inherits:
Object
  • Object
show all
Defined in:
lib/jazz_model/definition.rb

Constant Summary collapse

@@definitions =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name = nil, &block) ⇒ Definition

Returns a new instance of Definition.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/jazz_model/definition.rb', line 10

def initialize(name = nil, &block)
  if name.is_a?(Hash)
    raise ArgumentError, "Only one hash key expected" if name.keys.size > 1
    @name = name.keys[0]
    @included_definitions = name.values[0].is_a?(Array) ? name.values[0].map(&:to_sym) : [name.values[0].to_sym]
  else
    @name = name
    @included_definitions = []
  end
  
  @definition = block
  @loaded = false
  
  @@definitions << self
end

Instance Attribute Details

#definitionObject (readonly)

Returns the value of attribute definition.



7
8
9
# File 'lib/jazz_model/definition.rb', line 7

def definition
  @definition
end

#included_definitionsObject (readonly)

Returns the value of attribute included_definitions.



8
9
10
# File 'lib/jazz_model/definition.rb', line 8

def included_definitions
  @included_definitions
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/jazz_model/definition.rb', line 6

def name
  @name
end

Class Method Details

.[](name) ⇒ Object



30
31
32
# File 'lib/jazz_model/definition.rb', line 30

def self.[](name)
  definitions.find {|d| d.name.to_s == name.to_s }
end

.define(name, &block) ⇒ Object



34
35
36
# File 'lib/jazz_model/definition.rb', line 34

def self.define(name, &block)
  definition = self.new(name, &block)
end

.load(name) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/jazz_model/definition.rb', line 38

def self.load(name)
  if definition = self[name]
    definition.load
  else
    raise ArgumentError, "No definition known '#{name}'."
  end
end

Instance Method Details

#all_included_definitionsObject



60
61
62
# File 'lib/jazz_model/definition.rb', line 60

def all_included_definitions
  (@included_definitions.map {|d| self.class[d].try(:all_included_definitions) } + @included_definitions).flatten.compact.uniq
end

#ensure_loadedObject



46
47
48
# File 'lib/jazz_model/definition.rb', line 46

def ensure_loaded
  load unless loaded?
end

#loadObject



50
51
52
53
54
55
56
57
58
# File 'lib/jazz_model/definition.rb', line 50

def load
  (all_included_definitions.uniq - [self]).each do |d|
    self.class[d].ensure_loaded
  end
  
  instance_eval(&@definition)
  
  @loaded = true
end

#loaded?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/jazz_model/definition.rb', line 26

def loaded?
  !!@loaded
end