Class: Magnetic::Interface

Inherits:
Object show all
Includes:
Field::DSL
Defined in:
lib/magnetic/interface.rb

Defined Under Namespace

Modules: DSL

Instance Method Summary collapse

Methods included from Field::DSL

#field, #field_for, #fieldset, included

Constructor Details

#initialize(options = {}, &block) ⇒ Interface

Returns a new instance of Interface.



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

def initialize options = {}, &block
  options.to_options!
  records = options[:records]
  controller = options[:controller]
  @records = (( Array === records and ActiveRecord::Base === records[0] )) ? records : [records]
  @records = [] if records.nil?
  @controller = controller
  @mapping = []
  instance_eval &block if block
  post_initialize
end

Instance Method Details

#map(mapping) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/magnetic/interface.rb', line 23

def map mapping
  mapping.each do |key, value|
    key = key.to_s
    raise ArgumentError, 'empty key!' if key.empty?
    raise ArgumentError, 'no value!' if value.nil?
    @mapping << [key, value]
    if Magnetic::Field::Base === value
      field(value) unless field(value.name)
    end
  end
end

#map!Object



39
40
41
# File 'lib/magnetic/interface.rb', line 39

def map!
  @records.each{|record| map_record :record => record, :mapping => @mapping} unless @mapping.empty?
end

#map_record(options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/magnetic/interface.rb', line 43

def map_record options = {} 
  options.to_options!

  record = options.delete :record
  mapping = options.delete :mapping
  route = options.delete :route

  table_name = record.class.table_name
  id = record.id

  (( route ||= [] )) << "#{ table_name }[#{ id }]"

  mapping.each do |path, block|
    head, *tail = path.split '.'
    m, head, array, *ignored = %r/^(.*?)(\[\*?\])?$/o.match(head).to_a
    
    if array 
      subrecords = record.send head 
      subrecords = [subrecords] unless subrecords.class == Array
      subpath = tail.join '.'
      subblock = block
      submapping = [[ subpath, subblock ]]
      subrecords.each do |subrecord|
        subroute = route.clone 
        map_record :record => subrecord, :mapping => submapping, :route => subroute
      end
    else
      value = record.send head
      path = Magnetic.path(( [route, head].join('.') ))
      block.to_proc.call :path => path,
                         :value => value,
                         :model => record.class,
                         :table_name => table_name,
                         :column_name => head,
                         :record => record,
                         :interface => self,
                         :controller => @controller
    end
  end
end

#post_initializeObject



35
36
37
# File 'lib/magnetic/interface.rb', line 35

def post_initialize
  map!
end