View Javadoc
1   /*
2    * scriptable-dataset (https://github.com/hazendaz/scriptable-dataset)
3    *
4    * Copyright 2011-2024 Hazendaz.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * https://www.apache.org/licenses/LICENSE-2.0.txt
10   *
11   * Contributors:
12   *     Gunnar Morling
13   *     Hazendaz (Jeremy Landis).
14   */
15  package de.gmorling.scriptabledataset.handlers;
16  
17  import javax.script.Invocable;
18  import javax.script.ScriptEngine;
19  
20  import org.jruby.RubyObject;
21  
22  /**
23   * A <code>ScriptInvocationHandler</code> for JRuby scripts. It adds some commonly used imports to the begin of each
24   * script and converts Objects returned by the scripting engine into types processable by DBUnit.
25   */
26  public class JRubyScriptInvocationHandler implements ScriptInvocationHandler {
27  
28      /** The engine. */
29      private ScriptEngine engine;
30  
31      @Override
32      public String getLanguageName() {
33          return "jruby";
34      }
35  
36      @Override
37      public String preInvoke(String script) {
38          return "require 'date';" + script;
39      }
40  
41      @Override
42      public Object postInvoke(Object object) {
43  
44          if (object instanceof RubyObject) {
45              Invocable i = (Invocable) engine;
46  
47              RubyObject rubyObject = (RubyObject) object;
48              if (rubyObject.getMetaClass().getName().equals("DateTime")) {
49                  try {
50                      object = i.invokeMethod(object, "strftime", "%Y-%m-%d");
51                  } catch (Exception e) {
52                      throw new RuntimeException(e);
53                  }
54              }
55          }
56  
57          return object;
58      }
59  
60      @Override
61      public void setScriptEngine(ScriptEngine engine) {
62          this.engine = engine;
63      }
64  
65  }