Class: Transformator::Transformation

Inherits:
Object
  • Object
show all
Includes:
Dsl
Defined in:
lib/transformator/transformation.rb

Instance Method Summary collapse

Methods included from Dsl

#array, #cdata, #element, #element_from_xml, #elements_from_hash, #elements_from_xml, #find, #find_all, #xml_from_element

Constructor Details

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

Returns a new instance of Transformation.



5
6
7
8
9
10
11
12
13
# File 'lib/transformator/transformation.rb', line 5

def initialize(options = {}, &block)
  # make it possible to initialize a transformation with external data
  options.each_pair do |key, value|
    instance_variable_set "@#{key}".to_sym, value
  end

  @rules = []
  self.instance_eval(&block) if block
end

Instance Method Details

#apply(options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/transformator/transformation.rb', line 18

def apply(options = {})
  source = Transformator.document_from_object(options[:source] ||= options[:to])
  target = Transformator.document_from_object(options[:target])

  @rules.each do |rule|
    block = rule[:callable]
    path = rule[:path]
    type = rule[:type]

    # allow user do process source => source, target => target or target => source
    _source = options[:source] == :target ? target : source
    _target = options[:target] == :source ? source : target

    if type == :process
      if path.is_a?(Array)
        block.call(
          path.map do |_path| { _path => find_all(_source, _path) } end,
          _target
        )
      elsif path.is_a?(String)
        find_all(_source, path).each do |element_to_process|
          block.call(element_to_process, _target)
        end
      elsif path.is_a?(Symbol)
        if path == :document
          block.call(_source, _target)
        elsif path == :none
          block.call
        elsif path == :source
          block.call(source, _target)
        elsif path == :target
          block.call(target, _target)
        end
      end
    end
  end

  case options[:output_format] || @output_format || Transformator.determine_format(options[:source])
  when :hash then Transformator.hash_from_document(target)
  when :ox_document then target
  when :xml then Ox.dump(target, with_xml: true)
  else raise "Unknown output format!"
  end
end