Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rdp
Created May 22, 2009 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdp/116108 to your computer and use it in GitHub Desktop.
Save rdp/116108 to your computer and use it in GitHub Desktop.
1.module PyRuby
2. public
3.
4.
5. def self.require(base_name) # Creates a singleton (?) method named "require" in the namespace "PyRuby"
6. if $".include? base_name # In the current Ruby environment, is the name passed to require() in the list of already-imported modules?
7. return false # Do nothing
8. else
9. file = find_file base_name # find_file in same namespace
10. if file
11. load(file) # as is load. Tiny functions.
12. $" << base_name # Add the name to loaded modules (change system variable, should be privileged operation)
13. return true # sucess
14. end
15. end
16. end
17.
18. def self.load(file)
19. if file
20. txt = PyRuby.pyrb_convert file # preprocess
21. begin
22. Object.module_eval txt, file, 1
23. rescue SyntaxError => e
24. $stderr.print "Preprocessing Fail: " + $!
25. $stderr.print "-----------------------------------\n"
26. $stderr.print txt
27. raise
28. end
29. return true
30. end
31. false
32. end
33.
34. def self.find_file(fname)
35. if FileTest.exist?(fname)
36. return fname
37. else
38. $:.each do |path|
39. path = File.join(path, fname)
40. for ext in [ '.rb' ] do
41. p = path + ext
42. return p if FileTest.exist?(p)
43. end
44. end
45. end
46. end
47.
48. def self.pyrb_convert file
49. txt = ""
50. stack = []
51. found_pyrb_req = false
52. do_preprocess = false
53.
54. File.open file do |fh|
55. fh.each_line do |l|
56. l.chomp!
57. if l =~ /^__BEGIN__\s*$/
58. do_preprocess = true
59. elsif l =~ /^__END__\s*$/
60. do_preprocess = false
61. elsif do_preprocess
62.
63. # Do the indent preprocessing
64. indent = (l.gsub /\S.*/,'').length
65. stack.reverse.each do |pindent|
66. if indent <= pindent
67. case l.gsub /^\s*/,''
68. when /(else|end|rescue).*/
69. else
70. txt << (" " * pindent) + "end\n"
71. end
72. stack.pop
73. end
74. end
75. if l =~ /:\s*$/
76. stack.push indent
77. l.gsub! /:\s*$/,''
78. end
79. txt << l << "\n"
80.
81.
82. else
83. # Treat the code as normal Ruby code
84. # and pass straight through.
85. txt << l << "\n"
86. end
87. end
88. end
89. if do_preprocess
90. while not stack.empty?
91. txt << (" " * stack.pop) + "end\n"
92. end
93. end
94. txt
95. end
96.end
97.
98.alias __pyrb_load load
99.
100.def load base_name
101. PyRuby.load base_name
102.end
103.
104.def require base_name
105. PyRuby.require base_name
106.end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment