rene-adhearsion 0.8.6

Sign up to get free protection for your applications and to get access to all the features.
Files changed (115) hide show
  1. data/CHANGELOG +73 -0
  2. data/EVENTS +11 -0
  3. data/LICENSE +456 -0
  4. data/Rakefile +130 -0
  5. data/adhearsion.gemspec +173 -0
  6. data/app_generators/ahn/USAGE +5 -0
  7. data/app_generators/ahn/ahn_generator.rb +96 -0
  8. data/app_generators/ahn/templates/.ahnrc +34 -0
  9. data/app_generators/ahn/templates/README +8 -0
  10. data/app_generators/ahn/templates/Rakefile +25 -0
  11. data/app_generators/ahn/templates/components/ami_remote/ami_remote.rb +15 -0
  12. data/app_generators/ahn/templates/components/disabled/HOW_TO_ENABLE +7 -0
  13. data/app_generators/ahn/templates/components/disabled/restful_rpc/README.markdown +11 -0
  14. data/app_generators/ahn/templates/components/disabled/restful_rpc/example-client.rb +48 -0
  15. data/app_generators/ahn/templates/components/disabled/restful_rpc/restful_rpc.rb +91 -0
  16. data/app_generators/ahn/templates/components/disabled/restful_rpc/restful_rpc.yml +34 -0
  17. data/app_generators/ahn/templates/components/disabled/restful_rpc/spec/restful_rpc_spec.rb +263 -0
  18. data/app_generators/ahn/templates/components/disabled/sandbox/sandbox.rb +104 -0
  19. data/app_generators/ahn/templates/components/disabled/sandbox/sandbox.yml +2 -0
  20. data/app_generators/ahn/templates/components/disabled/stomp_gateway/README.markdown +47 -0
  21. data/app_generators/ahn/templates/components/disabled/stomp_gateway/stomp_gateway.rb +34 -0
  22. data/app_generators/ahn/templates/components/disabled/stomp_gateway/stomp_gateway.yml +12 -0
  23. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/README.markdown +3 -0
  24. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/xmpp_gateway.rb +11 -0
  25. data/app_generators/ahn/templates/components/disabled/xmpp_gateway/xmpp_gateway.yml +0 -0
  26. data/app_generators/ahn/templates/components/simon_game/simon_game.rb +56 -0
  27. data/app_generators/ahn/templates/config/startup.rb +83 -0
  28. data/app_generators/ahn/templates/dialplan.rb +3 -0
  29. data/app_generators/ahn/templates/events.rb +32 -0
  30. data/bin/ahn +28 -0
  31. data/bin/ahnctl +68 -0
  32. data/bin/jahn +42 -0
  33. data/examples/asterisk_manager_interface/standalone.rb +51 -0
  34. data/lib/adhearsion.rb +45 -0
  35. data/lib/adhearsion/cli.rb +228 -0
  36. data/lib/adhearsion/component_manager.rb +272 -0
  37. data/lib/adhearsion/component_manager/component_tester.rb +55 -0
  38. data/lib/adhearsion/component_manager/spec_framework.rb +24 -0
  39. data/lib/adhearsion/events_support.rb +84 -0
  40. data/lib/adhearsion/foundation/all.rb +15 -0
  41. data/lib/adhearsion/foundation/blank_slate.rb +3 -0
  42. data/lib/adhearsion/foundation/custom_daemonizer.rb +45 -0
  43. data/lib/adhearsion/foundation/event_socket.rb +204 -0
  44. data/lib/adhearsion/foundation/future_resource.rb +36 -0
  45. data/lib/adhearsion/foundation/metaprogramming.rb +17 -0
  46. data/lib/adhearsion/foundation/numeric.rb +13 -0
  47. data/lib/adhearsion/foundation/pseudo_guid.rb +10 -0
  48. data/lib/adhearsion/foundation/relationship_properties.rb +42 -0
  49. data/lib/adhearsion/foundation/string.rb +26 -0
  50. data/lib/adhearsion/foundation/synchronized_hash.rb +96 -0
  51. data/lib/adhearsion/foundation/thread_safety.rb +7 -0
  52. data/lib/adhearsion/host_definitions.rb +67 -0
  53. data/lib/adhearsion/initializer.rb +395 -0
  54. data/lib/adhearsion/initializer/asterisk.rb +87 -0
  55. data/lib/adhearsion/initializer/configuration.rb +321 -0
  56. data/lib/adhearsion/initializer/database.rb +60 -0
  57. data/lib/adhearsion/initializer/drb.rb +31 -0
  58. data/lib/adhearsion/initializer/freeswitch.rb +22 -0
  59. data/lib/adhearsion/initializer/ldap.rb +57 -0
  60. data/lib/adhearsion/initializer/rails.rb +41 -0
  61. data/lib/adhearsion/initializer/xmpp.rb +42 -0
  62. data/lib/adhearsion/logging.rb +92 -0
  63. data/lib/adhearsion/tasks.rb +16 -0
  64. data/lib/adhearsion/tasks/database.rb +5 -0
  65. data/lib/adhearsion/tasks/deprecations.rb +59 -0
  66. data/lib/adhearsion/tasks/generating.rb +20 -0
  67. data/lib/adhearsion/tasks/lint.rb +4 -0
  68. data/lib/adhearsion/tasks/testing.rb +37 -0
  69. data/lib/adhearsion/version.rb +33 -0
  70. data/lib/adhearsion/voip/asterisk.rb +4 -0
  71. data/lib/adhearsion/voip/asterisk/agi_server.rb +115 -0
  72. data/lib/adhearsion/voip/asterisk/commands.rb +1510 -0
  73. data/lib/adhearsion/voip/asterisk/config_generators/agents.conf.rb +140 -0
  74. data/lib/adhearsion/voip/asterisk/config_generators/config_generator.rb +101 -0
  75. data/lib/adhearsion/voip/asterisk/config_generators/queues.conf.rb +250 -0
  76. data/lib/adhearsion/voip/asterisk/config_generators/voicemail.conf.rb +240 -0
  77. data/lib/adhearsion/voip/asterisk/config_manager.rb +71 -0
  78. data/lib/adhearsion/voip/asterisk/manager_interface.rb +705 -0
  79. data/lib/adhearsion/voip/asterisk/manager_interface/ami_lexer.rb +1680 -0
  80. data/lib/adhearsion/voip/asterisk/manager_interface/ami_lexer.rl.rb +340 -0
  81. data/lib/adhearsion/voip/asterisk/manager_interface/ami_messages.rb +78 -0
  82. data/lib/adhearsion/voip/asterisk/manager_interface/ami_protocol_lexer_machine.rl +87 -0
  83. data/lib/adhearsion/voip/asterisk/special_dial_plan_managers.rb +80 -0
  84. data/lib/adhearsion/voip/asterisk/super_manager.rb +19 -0
  85. data/lib/adhearsion/voip/call.rb +497 -0
  86. data/lib/adhearsion/voip/call_routing.rb +64 -0
  87. data/lib/adhearsion/voip/commands.rb +9 -0
  88. data/lib/adhearsion/voip/constants.rb +39 -0
  89. data/lib/adhearsion/voip/conveniences.rb +18 -0
  90. data/lib/adhearsion/voip/dial_plan.rb +246 -0
  91. data/lib/adhearsion/voip/dsl/dialing_dsl.rb +151 -0
  92. data/lib/adhearsion/voip/dsl/dialing_dsl/dialing_dsl_monkey_patches.rb +37 -0
  93. data/lib/adhearsion/voip/dsl/dialplan/control_passing_exception.rb +27 -0
  94. data/lib/adhearsion/voip/dsl/dialplan/dispatcher.rb +124 -0
  95. data/lib/adhearsion/voip/dsl/dialplan/parser.rb +69 -0
  96. data/lib/adhearsion/voip/dsl/dialplan/thread_mixin.rb +16 -0
  97. data/lib/adhearsion/voip/dsl/numerical_string.rb +115 -0
  98. data/lib/adhearsion/voip/freeswitch/basic_connection_manager.rb +48 -0
  99. data/lib/adhearsion/voip/freeswitch/event_handler.rb +58 -0
  100. data/lib/adhearsion/voip/freeswitch/freeswitch_dialplan_command_factory.rb +129 -0
  101. data/lib/adhearsion/voip/freeswitch/inbound_connection_manager.rb +38 -0
  102. data/lib/adhearsion/voip/freeswitch/oes_server.rb +195 -0
  103. data/lib/adhearsion/voip/menu_state_machine/calculated_match.rb +80 -0
  104. data/lib/adhearsion/voip/menu_state_machine/matchers.rb +123 -0
  105. data/lib/adhearsion/voip/menu_state_machine/menu_builder.rb +58 -0
  106. data/lib/adhearsion/voip/menu_state_machine/menu_class.rb +149 -0
  107. data/lib/adhearsion/xmpp/connection.rb +61 -0
  108. data/lib/theatre.rb +151 -0
  109. data/lib/theatre/README.markdown +64 -0
  110. data/lib/theatre/callback_definition_loader.rb +84 -0
  111. data/lib/theatre/guid.rb +23 -0
  112. data/lib/theatre/invocation.rb +121 -0
  113. data/lib/theatre/namespace_manager.rb +153 -0
  114. data/lib/theatre/version.rb +2 -0
  115. metadata +241 -0
data/bin/jahn ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env jruby
2
+
3
+ # This "jahn" script is "ahn" for JRUBY!
4
+
5
+ # Adhearsion, open source collaboration framework
6
+ # Copyright (C) 2006,2007,2008 Jay Phillips
7
+ #
8
+ # This library is free software; you can redistribute it and/or modify it under
9
+ # the terms of the GNU Lesser General Public License as published by the Free
10
+ # Software Foundation; either version 2.1 of the License, or (at your option)
11
+ # any later version.
12
+ #
13
+ # This library is distributed in the hope that it will be useful, but WITHOUT
14
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15
+ # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16
+ # details.
17
+ #
18
+ # You should have received a copy of the GNU Lesser General Public License along
19
+ # with this library; if not, write to the Free Software Foundation, Inc.,
20
+ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+
22
+ $:.unshift File.expand_path(File.dirname(__FILE__) + "/../lib")
23
+
24
+ require 'rubygems'
25
+ require 'adhearsion'
26
+ require 'adhearsion/cli'
27
+
28
+ # jahn will soon have JRuby-specific behavior such as creating a compiled .jar
29
+ # file from an app.
30
+ # require 'adhearsion/jruby'
31
+
32
+ abort(<<-MESSAGE) unless RUBY_PLATFORM =~ /java/
33
+ You must use jahn with JRuby! Are you running this script after installing Adhearsion with non-JRuby RubyGems?
34
+
35
+ If you don't want to install Adhearsion with the JRuby version of RubyGems, try running jahn directly with an absolute path:
36
+
37
+ #{File.expand_path(__FILE__)} start your_app_name
38
+
39
+ Note: You must have the jruby executable in your $PATH and $JRUBY_HOME set.
40
+ MESSAGE
41
+
42
+ Adhearsion::CLI::AhnCommand.execute!
@@ -0,0 +1,51 @@
1
+ # This is a file which shows you how to use the Asterisk Manager Interface library in a standalone Ruby script.
2
+
3
+ PATH_TO_ADHEARSION = File.join(File.dirname(__FILE__), "/../..")
4
+
5
+ MANAGER_CONNECTION_INFORMATION = {
6
+ :host => "10.0.1.97",
7
+ :username => "jicksta",
8
+ :password => "roflcopter",
9
+ :events => true
10
+ }
11
+
12
+ require 'rubygems'
13
+ begin
14
+ require 'adhearsion'
15
+ rescue LoadError
16
+ begin
17
+ require File.join(PATH_TO_ADHEARSION, "/lib/adhearsion")
18
+ rescue LoadError
19
+ abort "Could not find Adhearsion! Please update the PATH_TO_ADHEARSION constant in this file"
20
+ end
21
+ end
22
+
23
+ require 'adhearsion/voip/asterisk/manager_interface'
24
+
25
+ # If you'd like to see the AMI protocol data, change this to :debug
26
+ Adhearsion::Logging.logging_level = :warn
27
+
28
+ # This makes addressing the ManagerInterface class a little cleaner
29
+ include Adhearsion::VoIP::Asterisk::Manager
30
+
31
+ # Let's instantiate a new ManagerInterface object and have it automatically connect using the Hash we defined above.
32
+ interface = ManagerInterface.connect MANAGER_CONNECTION_INFORMATION
33
+
34
+ # Send an AMI action with our new ManagerInterface object. This will return an Array of SIPPeer events.
35
+ sip_peers = interface.send_action "SIPPeers"
36
+
37
+ # Pretty-print the SIP peers on the server
38
+
39
+ if sip_peers.any?
40
+ sip_peers.each do |peer|
41
+ # Uncomment the following line to view all the headers for each peer.
42
+ # p peer.headers
43
+
44
+ peer_name = peer.headers["ObjectName"]
45
+ peer_status = peer.headers["Status"]
46
+
47
+ puts "#{peer_name}: #{peer_status}"
48
+ end
49
+ else
50
+ puts "This Asterisk server has no SIP peers!"
51
+ end
data/lib/adhearsion.rb ADDED
@@ -0,0 +1,45 @@
1
+ # Check the Ruby version
2
+ STDERR.puts "WARNING: You are running Adhearsion in an unsupported
3
+ version of Ruby (Ruby #{RUBY_VERSION} #{RUBY_RELEASE_DATE})!
4
+ Please upgrade to at least Ruby v1.8.5." if RUBY_VERSION < "1.8.5"
5
+
6
+ $: << File.expand_path(File.dirname(__FILE__))
7
+
8
+ require 'rubygems'
9
+
10
+ require 'adhearsion/version'
11
+ require 'adhearsion/voip/call'
12
+ require 'adhearsion/voip/dial_plan'
13
+ require 'adhearsion/voip/asterisk/special_dial_plan_managers'
14
+ require 'adhearsion/foundation/all'
15
+ require 'adhearsion/events_support'
16
+ require 'adhearsion/logging'
17
+ require 'adhearsion/component_manager'
18
+ require 'adhearsion/initializer/configuration'
19
+ require 'adhearsion/initializer'
20
+ require 'adhearsion/voip/dsl/numerical_string'
21
+ require 'adhearsion/voip/dsl/dialplan/parser'
22
+ require 'adhearsion/voip/commands'
23
+ require 'adhearsion/voip/asterisk/commands'
24
+ require 'adhearsion/voip/dsl/dialing_dsl'
25
+ require 'adhearsion/voip/call_routing'
26
+
27
+ begin
28
+ # Try ActiveSupport >= 2.3.0
29
+ require 'active_support/all'
30
+ rescue LoadError
31
+ # Assume ActiveSupport < 2.3.0
32
+ require 'active_support'
33
+ end
34
+
35
+ module Adhearsion
36
+ # Sets up the Gem require path.
37
+ AHN_INSTALL_DIR = File.expand_path(File.dirname(__FILE__) + "/..")
38
+ AHN_CONFIG = Configuration.new
39
+
40
+ ##
41
+ # This Array holds all the Threads whose life matters. Adhearsion will not exit until all of these have died.
42
+ #
43
+ IMPORTANT_THREADS = []
44
+
45
+ end
@@ -0,0 +1,228 @@
1
+ require 'fileutils'
2
+
3
+ module Adhearsion
4
+ module CLI
5
+ module AhnCommand
6
+ USAGE = <<USAGE
7
+ Usage:
8
+ ahn create /path/to/directory
9
+ ahn start [daemon] [/path/to/directory]
10
+ ahn version|-v|--v|-version|--version
11
+ ahn help|-h|--h|--help|-help
12
+
13
+ ahn enable component COMPONENT_NAME
14
+ ahn disable component COMPONENT_NAME
15
+ ahn create component COMPONENT_NAME
16
+ USAGE
17
+
18
+ def self.execute!
19
+ CommandHandler.send(*parse_arguments)
20
+ rescue CommandHandler::CLIException => error
21
+ fail_and_print_usage error
22
+ end
23
+
24
+ ##
25
+ # Provides a small abstraction of Kernel::abort().
26
+ #
27
+ def self.fail_and_print_usage(error)
28
+ Kernel.abort "#{error.message}\n\n#{USAGE}"
29
+ end
30
+
31
+ def self.parse_arguments(args=ARGV.clone)
32
+ action = args.shift
33
+ case action
34
+ when /^-?-?h(elp)?$/, nil then [:help]
35
+ when /^-?-?v(ersion)?$/ then [:version]
36
+ when "create"
37
+ [:create, *args]
38
+ when 'start'
39
+ pid_file_regexp = /^--pid-file=(.+)$/
40
+ if args.size > 3
41
+ fail_and_print_usage "Too many arguments supplied!" if args.size > 3
42
+ elsif args.size == 3
43
+ fail_and_print_usage "Unrecognized final argument #{args.last}" unless args.last =~ pid_file_regexp
44
+ pid_file = args.pop[pid_file_regexp, 1]
45
+ else
46
+ pid_file = nil
47
+ end
48
+
49
+ if args.first == 'daemon' && args.size == 2
50
+ path = args.last
51
+ daemon = true
52
+ elsif args.size == 1
53
+ path, daemon = args.first, false
54
+ else
55
+ fail_and_print_usage "Invalid format for the start CLI command!"
56
+ end
57
+ [:start, path, daemon, pid_file]
58
+ when '-'
59
+ [:start, Dir.pwd]
60
+ when "enable", "disable"
61
+ if args.size == 1
62
+ raise CommandHandler::UnknownCommand, "Must supply an argument for what you wish to #{action}"
63
+ elsif args.size == 2
64
+ [action, *args]
65
+ else
66
+ raise CommandHandler::UnknownCommand, "Too many arguments supplied!"
67
+ end
68
+ else
69
+ [action, *args]
70
+ end
71
+ end
72
+
73
+ module CommandHandler
74
+ class << self
75
+
76
+ def create(*args)
77
+ if args.size.zero?
78
+ raise CommandHandler::UnknownCommand.new("Must specify something to create!")
79
+ elsif args.size == 1
80
+ # We're creating a project
81
+ path = args.first
82
+ require 'rubigen'
83
+ require 'rubigen/scripts/generate'
84
+ source = RubiGen::PathSource.new(:application,
85
+ File.join(File.dirname(__FILE__), "../../app_generators"))
86
+ RubiGen::Base.reset_sources
87
+ RubiGen::Base.append_sources source
88
+ RubiGen::Scripts::Generate.new.run([path], :generator => 'ahn')
89
+ elsif args.size == 2
90
+ # We're creating a feature (e.g. a component)
91
+ feature_type, component_name = args
92
+
93
+ if feature_type != "component"
94
+ # At the moment, only components can be created.
95
+ raise CommandHandler::UnknownCommand.new("Don't know how to create '#{feature_type}'")
96
+ end
97
+
98
+ if component_name !~ /^[a-z][\w_]+$/
99
+ raise CommandHandler::ComponentError.new("Component name must be lowercase alphanumeric characters " +
100
+ "and begin with a character")
101
+ end
102
+
103
+ app_path = PathString.from_application_subdirectory Dir.pwd
104
+
105
+ raise PathInvalid.new(Dir.pwd) if app_path.nil?
106
+
107
+ new_component_dir = app_path + "/components/#{component_name}"
108
+ raise ComponentError.new("Component #{component_name} already exists!") if File.exists?(new_component_dir)
109
+
110
+ # Everything's good. Let's create the component
111
+ Dir.mkdir new_component_dir
112
+ File.open(new_component_dir + "/#{component_name}.rb","w") do |file|
113
+ file.puts <<-RUBY
114
+ # See http://docs.adhearsion.com for more information on how to write components or
115
+ # look at the examples in newly-created projects.
116
+ RUBY
117
+ end
118
+ File.open(new_component_dir + "/#{component_name}.yml","w") do |file|
119
+ file.puts '# You can use this file for component-specific configuration.'
120
+ end
121
+ puts "Created blank component '#{component_name}' at components/#{component_name}"
122
+ else
123
+ raise CommandHandler::UnknownCommand.new("Provided too many arguments to 'create'")
124
+ end
125
+ end
126
+
127
+ def start(path, daemon=false, pid_file=nil)
128
+ raise PathInvalid, path unless File.exists? path + "/.ahnrc"
129
+ Adhearsion::Initializer.start path, :daemon => daemon, :pid_file => pid_file
130
+ end
131
+
132
+ def version
133
+ puts "Adhearsion v#{Adhearsion::VERSION::STRING}"
134
+ end
135
+
136
+ def help
137
+ puts USAGE
138
+ end
139
+
140
+ def enable(type, name)
141
+ case type
142
+ when "component"
143
+ app_path = PathString.from_application_subdirectory Dir.pwd
144
+ if app_path
145
+ disabled_component_path = File.join app_path, "components", "disabled", name
146
+ disabled_components_path = File.join app_path, "components", "disabled"
147
+ enabled_component_path = File.join app_path, "components", name
148
+ if File.directory? disabled_component_path
149
+ FileUtils.mv disabled_component_path, enabled_component_path
150
+ puts "Enabled component #{name}"
151
+ elsif File.directory? enabled_component_path
152
+ raise ComponentError.new("This component is already enabled.")
153
+ elsif !File.directory? disabled_components_path
154
+ raise ComponentError.new("There is no components/disabled directory!")
155
+ else
156
+ raise ComponentError.new("The requested component was not found.")
157
+ end
158
+ else
159
+ raise PathInvalid.new(Dir.pwd)
160
+ end
161
+ else
162
+ raise UnknownCommand.new("enable #{type}")
163
+ end
164
+ end
165
+
166
+ def disable(type, name)
167
+ case type
168
+ when "component"
169
+ app_path = PathString.from_application_subdirectory Dir.pwd
170
+ if app_path
171
+ disabled_dir = File.join app_path, "components", "disabled"
172
+
173
+ disabled_component_path = File.join disabled_dir, name
174
+ enabled_component_path = File.join app_path, "components", name
175
+
176
+ Dir.mkdir disabled_dir unless File.directory?(disabled_dir)
177
+
178
+ if File.directory? enabled_component_path
179
+ if File.directory?(disabled_component_path)
180
+ raise ComponentError.new("There is already a disabled component at #{disabled_component_path}")
181
+ else
182
+ FileUtils.mv enabled_component_path, disabled_component_path
183
+ puts "Disabled component #{name}"
184
+ end
185
+ else
186
+ raise ComponentError.new("Could not find component #{name} at #{enabled_component_path} !")
187
+ end
188
+ else
189
+ raise PathInvalid.new(Dir.pwd)
190
+ end
191
+ else
192
+ raise UnknownCommand.new("disable #{type}")
193
+ end
194
+ end
195
+
196
+ def method_missing(action, *args)
197
+ raise UnknownCommand, [action, *args] * " "
198
+ end
199
+
200
+ private
201
+
202
+ end
203
+
204
+ class CLIException < StandardError; end
205
+
206
+ class UnknownCommand < CLIException
207
+ def initialize(cmd)
208
+ super "Unknown command: #{cmd}"
209
+ end
210
+ end
211
+
212
+ class ComponentError < CLIException; end
213
+
214
+ class UnknownProject < CLIException
215
+ def initialize(project)
216
+ super "Application #{project} does not exist! Have you installed it?"
217
+ end
218
+ end
219
+
220
+ class PathInvalid < CLIException
221
+ def initialize(path)
222
+ super "Directory #{path} does not belong to an Adhearsion project!"
223
+ end
224
+ end
225
+ end
226
+ end
227
+ end
228
+ end
@@ -0,0 +1,272 @@
1
+ module Adhearsion
2
+ module Components
3
+
4
+ mattr_accessor :component_manager
5
+
6
+ class ConfigurationError < Exception; end
7
+
8
+ class ComponentManager
9
+
10
+ class << self
11
+
12
+ def scopes_valid?(*scopes)
13
+ unrecognized_scopes = (scopes.flatten - SCOPE_NAMES).map(&:inspect)
14
+ raise ArgumentError, "Unrecognized scopes #{unrecognized_scopes.to_sentence}" if unrecognized_scopes.any?
15
+ true
16
+ end
17
+
18
+ end
19
+
20
+ SCOPE_NAMES = [:dialplan, :events, :generators, :rpc, :global]
21
+
22
+ attr_reader :scopes, :lazy_config_loader
23
+ def initialize(path_to_container_directory)
24
+ @path_to_container_directory = path_to_container_directory
25
+ @scopes = SCOPE_NAMES.inject({}) do |scopes, name|
26
+ scopes[name] = Module.new
27
+ scopes
28
+ end
29
+ @lazy_config_loader = LazyConfigLoader.new(self)
30
+ end
31
+
32
+ ##
33
+ # Includes the anonymous Module created for the :global scope in Object, making its methods globally accessible.
34
+ #
35
+ def globalize_global_scope!
36
+ Object.send :include, @scopes[:global]
37
+ end
38
+
39
+ def load_components
40
+ components = Dir.glob(File.join(@path_to_container_directory + "/*")).select do |path|
41
+ File.directory?(path)
42
+ end
43
+ components.map! { |path| File.basename path }
44
+ components.each do |component|
45
+ next if component == "disabled"
46
+ component_file = File.join(@path_to_container_directory, component, 'lib', component + ".rb")
47
+ if File.exists? component_file
48
+ load_file component_file
49
+ next
50
+ end
51
+
52
+ # Try the old-style components/<component>/<component>.rb
53
+ component_file = File.join(@path_to_container_directory, component, component + ".rb")
54
+ if File.exists? component_file
55
+ load_file component_file
56
+ else
57
+ ahn_log.warn "Component directory does not contain a matching .rb file! Was expecting #{component_file.inspect}"
58
+ end
59
+ end
60
+
61
+ # Load configured system- or gem-provided components
62
+ AHN_CONFIG.components_to_load.each do |component|
63
+ require component
64
+ end
65
+
66
+ end
67
+
68
+ ##
69
+ # Loads the configuration file for a given component name.
70
+ #
71
+ # @return [Hash] The loaded YAML for the given component name. An empty Hash if no YAML file exists.
72
+ #
73
+ def configuration_for_component_named(component_name)
74
+ # Look for configuration in #{AHN_ROOT}/config/components first
75
+ if File.exists?("#{AHN_ROOT}/config/components/#{component_name}.yml")
76
+ return YAML.load_file "#{AHN_ROOT}/config/components/#{component_name}.yml"
77
+ end
78
+
79
+ # Next try the local app component directory
80
+ component_dir = File.join(@path_to_container_directory, component_name)
81
+ config_file = File.join component_dir, "#{component_name}.yml"
82
+ if File.exists?(config_file)
83
+ YAML.load_file config_file
84
+ else
85
+ # Nothing found? Return an empty hash
86
+ ahn_log.warn "No configuration found for requested component #{component_name}"
87
+ return {}
88
+ end
89
+ end
90
+
91
+ def extend_object_with(object, *scopes)
92
+ raise ArgumentError, "Must supply at least one scope!" if scopes.empty?
93
+
94
+ self.class.scopes_valid? scopes
95
+
96
+ scopes.each do |scope|
97
+ methods = @scopes[scope]
98
+ if object.kind_of?(Module)
99
+ object.send :include, methods
100
+ else
101
+ object.extend methods
102
+ end
103
+ end
104
+ object
105
+ end
106
+
107
+ def load_code(code)
108
+ load_container ComponentDefinitionContainer.load_code(code)
109
+ end
110
+
111
+ def load_file(filename)
112
+ load_container ComponentDefinitionContainer.load_file(filename)
113
+ end
114
+
115
+ def require(filename)
116
+ load_container ComponentDefinitionContainer.require(filename)
117
+ end
118
+
119
+ protected
120
+
121
+ def load_container(container)
122
+ container.constants.each do |constant_name|
123
+ constant_value = container.const_get(constant_name)
124
+ Object.const_set(constant_name, constant_value)
125
+ end
126
+ metadata = container.metaclass.send(:instance_variable_get, :@metadata)
127
+ metadata[:initialization_block].call if metadata[:initialization_block]
128
+
129
+ self.class.scopes_valid? metadata[:scopes].keys
130
+
131
+ metadata[:scopes].each_pair do |scope, method_definition_blocks|
132
+ method_definition_blocks.each do |method_definition_block|
133
+ @scopes[scope].module_eval(&method_definition_block)
134
+ end
135
+ end
136
+ container
137
+ end
138
+
139
+ class ComponentDefinitionContainer < Module
140
+
141
+ class << self
142
+ def load_code(code)
143
+ new.tap do |instance|
144
+ instance.module_eval code
145
+ end
146
+ end
147
+
148
+ def load_file(filename)
149
+ new.tap do |instance|
150
+ instance.module_eval File.read(filename), filename
151
+ end
152
+ end
153
+
154
+ def require(filename)
155
+ filename = filename + ".rb" if !(filename =~ /\.rb$/)
156
+ begin
157
+ # Try loading the exact filename first
158
+ load_file(filename)
159
+ rescue LoadError, Errno::ENOENT
160
+ end
161
+
162
+ # Next try Rubygems
163
+ filepath = get_gem_path_for(filename)
164
+ return load_file(filepath) if !filepath.nil?
165
+
166
+ # Finally try the system search path
167
+ filepath = get_system_path_for(filename)
168
+ return load_file(filepath) if !filepath.nil?
169
+
170
+ # Raise a LoadError exception if the file is still not found
171
+ raise LoadError "File not found: #{filename}"
172
+ end
173
+
174
+ end
175
+
176
+ def initialize(&block)
177
+ # Hide our instance variables in the singleton class
178
+ metadata = {}
179
+ metaclass.send(:instance_variable_set, :@metadata, metadata)
180
+
181
+ metadata[:scopes] = ComponentManager::SCOPE_NAMES.inject({}) do |scopes, name|
182
+ scopes[name] = []
183
+ scopes
184
+ end
185
+
186
+ super
187
+
188
+ meta_def(:initialize) { raise "This object has already been instantiated. Are you sure you didn't mean initialization()?" }
189
+ end
190
+
191
+ def methods_for(*scopes, &block)
192
+ raise ArgumentError if scopes.empty?
193
+
194
+ ComponentManager.scopes_valid? scopes
195
+
196
+ metadata = metaclass.send(:instance_variable_get, :@metadata)
197
+ scopes.each { |scope| metadata[:scopes][scope] << block }
198
+ end
199
+
200
+ def initialization(&block)
201
+ # Raise an exception if the initialization block has already been set
202
+ metadata = metaclass.send(:instance_variable_get, :@metadata)
203
+ if metadata[:initialization_block]
204
+ raise "You should only have one initialization() block!"
205
+ else
206
+ metadata[:initialization_block] = block
207
+ end
208
+ end
209
+ alias initialisation initialization
210
+
211
+ protected
212
+
213
+ class << self
214
+ def self.method_added(method_name)
215
+ @methods ||= []
216
+ @methods << method_name
217
+ end
218
+
219
+ def get_gem_path_for(filename)
220
+ # Look for component files provided by rubygems
221
+ spec = Gem.searcher.find(filename)
222
+ return nil if spec.nil?
223
+ File.join(spec.full_gem_path, spec.require_path, filename)
224
+ rescue NameError
225
+ # In case Rubygems are not available
226
+ nil
227
+ end
228
+
229
+ def get_system_path_for(filename)
230
+ $:.each do |path|
231
+ filepath = File.join(path, filename)
232
+ return filepath if File.exists?(filepath)
233
+ end
234
+
235
+ # Not found? Return nil
236
+ return nil
237
+ end
238
+ end
239
+
240
+ end
241
+
242
+ class ComponentMethodDefinitionContainer < Module
243
+ class << self
244
+ def method_added(method_name)
245
+ @methods ||= []
246
+ @methods << method_name
247
+ end
248
+ end
249
+
250
+ attr_reader :scopes
251
+ def initialize(*scopes, &block)
252
+ @scopes = []
253
+ super(&block)
254
+ end
255
+
256
+ end
257
+
258
+ class LazyConfigLoader
259
+ def initialize(component_manager)
260
+ @component_manager = component_manager
261
+ end
262
+
263
+ def method_missing(component_name)
264
+ config = @component_manager.configuration_for_component_named(component_name.to_s)
265
+ (class << self; self; end).send(:define_method, component_name) { config }
266
+ config
267
+ end
268
+ end
269
+
270
+ end
271
+ end
272
+ end