Last active
January 8, 2016 23:58
-
-
Save alan-morey/0e49ca4563d056f05782 to your computer and use it in GitHub Desktop.
Wrapper for running anonymous code blocks in Salesforce, print() and println() allow you to write messages to a single output stream and have the out rendered to debug log and also in an AlertException. The AlertException is the always thrown at end of execution which ensures that nothing is ever committed to the Database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class AnonApp implements MainMethod { | |
final String[] OUT = new String[0]; | |
public static void run(Type clazz) { | |
AnonApp app = (AnonApp) clazz.newInstance(); | |
app.run(); | |
} | |
public void run() { | |
try { | |
((MainMethod) this).main(); | |
} finally { | |
alertOutput(); | |
} | |
} | |
protected void println(Object obj) { | |
print(obj); | |
OUT.add('\n'); | |
} | |
protected void print(Object obj) { | |
OUT.add(String.valueOf(obj)); | |
} | |
void alertOutput() { | |
String output = String.join(OUT, ''); | |
System.debug(output); | |
throw new AlertException(output); | |
} | |
class AlertException extends Exception {} | |
public interface MainMethod { | |
void main(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main extends AnonApp { | |
public void main() { | |
println('foo'); | |
print('bar'); | |
} | |
} | |
AnonApp.run(Main.class); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment