Class: Coupler::Models::Transformer

Inherits:
Sequel::Model
  • Object
show all
Includes:
CommonModel
Defined in:
lib/coupler/models/transformer.rb,
lib/coupler/models/transformer/runner.rb

Defined Under Namespace

Classes: Runner

Constant Summary collapse

TYPES =
%w{string integer datetime}
EXAMPLES =
{
  'string'   => 'Test',
  'integer'  => 123,
  'datetime' => lambda { Time.now }
}

Instance Method Summary collapse

Methods included from CommonModel

#after_destroy, #after_save, #before_create, #before_save, #before_update, included, #save!, #touch!

Instance Method Details

#accepts_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/coupler/models/transformer.rb', line 15

def accepts_type?(type)
  allowed_types.is_a?(Array) && allowed_types.include?(type)
end

#field_changes(*fields) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/coupler/models/transformer.rb', line 58

def field_changes(*fields)
  fields.inject({}) do |result, field|
    result[field.id] = hash = {}
    if result_type != 'same'
      hash[:type] = result_type.to_sym

      # FIXME: don't use db_type anymore
      hash[:db_type] =
        case result_type
        when 'integer'  then 'int(11)'
        when 'string'   then 'varchar(255)'
        when 'datetime' then 'datetime'
        end
    end
    result
  end
end

#previewObject



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
# File 'lib/coupler/models/transformer.rb', line 27

def preview
  return nil  if allowed_types.nil? || code.nil? || code == ""

  result = {'success' => true}
  examples = EXAMPLES.reject { |k, v| !allowed_types.include?(k) }
  examples.each_pair do |type, obj|
    obj = obj.call  if obj.is_a?(Proc)
    result[type] = { :in => obj }
    begin
      transform(result[type], {:in => :in, :out => :out})

      expected_type = result_type == 'same' ? type : result_type
      actual_type = case result[type][:out]
                    when String then "string"
                    when Fixnum then "integer"
                    when Time, Date, DateTime then "datetime"
                    when NilClass then "null"
                    end

      if actual_type != "null" && expected_type != actual_type
        raise TypeError, "expected #{expected_type}, got #{actual_type}"
      end

    rescue Exception => e
      result[type][:out] = e
      result['success'] = false
    end
  end
  result
end

#transform(data, options) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/coupler/models/transformer.rb', line 19

def transform(data, options)
  input = data[options[:in]]
  runner = Runner.new(code, input)
  output = runner.run
  data[options[:out]] = output
  data
end