Class: Transformator::Transformation
- Inherits:
-
Object
- Object
- Transformator::Transformation
- Includes:
- Dsl
- Defined in:
- lib/transformator/transformation.rb
Instance Method Summary collapse
- #apply(options = {}) ⇒ Object
-
#initialize(options = {}, &block) ⇒ Transformation
constructor
A new instance of Transformation.
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( = {}, &block) # make it possible to initialize a transformation with external data .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 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/transformator/transformation.rb', line 18 def apply( = {}) source = Transformator.document_from_object([:source] ||= [:to]) target = Transformator.document_from_object([:target]) @rules.each do |rule| block = rule[:callable] path = rule[:path] type = rule[:type] # allow user to set source/target freely _source = if (source_callable = rule[:source]).respond_to?(:call) source_callable.call else source end _target = if (target_callable = rule[:target]).respond_to?(:call) target_callable.call else target end 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 [:output_format] || @output_format || Transformator.determine_format([: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 |