Class: Peanuts::Mapper

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/peanuts/mapper.rb

Defined Under Namespace

Classes: Footprint, MappingFootprint, ReaderFootprint

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ns_context = nil, default_ns = nil) ⇒ Mapper

Returns a new instance of Mapper.



16
17
18
19
20
# File 'lib/peanuts/mapper.rb', line 16

def initialize(ns_context = nil, default_ns = nil)
  @ns_context, @default_ns = ns_context, default_ns
  @mappings, @footprints = [], {}
  @namespaces = ns_context ? Hash.new {|h, k| ns_context[k] || raise(IndexError) } : {}
end

Instance Attribute Details

#default_nsObject

Returns the value of attribute default_ns.



14
15
16
# File 'lib/peanuts/mapper.rb', line 14

def default_ns
  @default_ns
end

#namespacesObject (readonly)

Returns the value of attribute namespaces.



13
14
15
# File 'lib/peanuts/mapper.rb', line 13

def namespaces
  @namespaces
end

#ns_contextObject (readonly)

Returns the value of attribute ns_context.



13
14
15
# File 'lib/peanuts/mapper.rb', line 13

def ns_context
  @ns_context
end

#rootObject

Returns the value of attribute root.



13
14
15
# File 'lib/peanuts/mapper.rb', line 13

def root
  @root
end

#schemaObject

Returns the value of attribute schema.



14
15
16
# File 'lib/peanuts/mapper.rb', line 14

def schema
  @schema
end

Class Method Details

.of(cls) ⇒ Object



7
8
9
# File 'lib/peanuts/mapper.rb', line 7

def self.of(cls)
  cls.send(:mapper)
end

Instance Method Details

#<<(mapping) ⇒ Object



33
34
35
36
37
# File 'lib/peanuts/mapper.rb', line 33

def <<(mapping)
  fp = MappingFootprint.new(mapping)
  raise "mapping already defined for #{fp}" if @footprints.include?(fp)
  @mappings << (@footprints[fp] = mapping)
end

#clear(nut) ⇒ Object



66
67
68
# File 'lib/peanuts/mapper.rb', line 66

def clear(nut)
  each {|m| m.clear(nut) }
end

#define_accessors(type) ⇒ Object



39
40
41
# File 'lib/peanuts/mapper.rb', line 39

def define_accessors(type)
  each {|m| m.define_accessors(type) }
end

#each(&block) ⇒ Object



29
30
31
# File 'lib/peanuts/mapper.rb', line 29

def each(&block)
  @mappings.each(&block)
end

#read(nut, reader) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/peanuts/mapper.rb', line 43

def read(nut, reader)
  rdfp = ReaderFootprint.new(reader)
  reader.each do
    m = @footprints[rdfp]
    m.read(nut, reader) if m
  end
  nut
end

#write(nut, writer) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/peanuts/mapper.rb', line 52

def write(nut, writer)
  @root.write(writer) do |w|
    w.write_namespaces('' => default_ns) if default_ns
    w.write_namespaces(namespaces)
    write_children(nut, w)
  end
  nil
end

#write_children(nut, writer) ⇒ Object



61
62
63
64
# File 'lib/peanuts/mapper.rb', line 61

def write_children(nut, writer)
  each {|m| m.write(nut, writer) } if nut
  nil
end