Skip to content

Commit

Permalink
small fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
al6x committed Oct 30, 2011
1 parent 2805dcd commit 1a9dd98
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 15 deletions.
17 changes: 9 additions & 8 deletions lib/class_loader/class_loader.rb
Expand Up @@ -72,20 +72,21 @@ def load namespace, const
end
end

# Dynamic class loading is not thread safe (known Ruby bug), to workaround it
# You can forcefully preload all Your classes in production when Your app starts.
def preload path
# Eagerly load all classes in paths.
def preload *paths
monitor.synchronize do
Dir.glob("#{path}/**/*.rb").each do |class_path|
class_file_name = class_path.sub("#{path}/", '').sub(/\.rb$/, '')
require class_file_name
paths.each do |path|
Dir.glob("#{path}/**/*.rb").each do |class_path|
class_file_name = class_path.sub("#{path}/", '').sub(/\.rb$/, '')
require class_file_name
end
end
end
end

# Watch and reload files.
def watch path
watcher.paths << path
def watch *paths
paths.each{|path| watcher.paths << path}
watcher.start
end

Expand Down
1 change: 1 addition & 0 deletions lib/class_loader/watcher.rb
Expand Up @@ -33,6 +33,7 @@ def check
class_file_name = class_path.sub "#{path}/", ''
warn "reloading #{class_file_name}"
load class_file_name
files[class_path] = updated_at
end
else
files[class_path] = updated_at
Expand Down
22 changes: 15 additions & 7 deletions readme.md
@@ -1,4 +1,4 @@
# Automatically find, load and reload classes
# ClassLoader automatically finds, loads and reloads classes

Suppose there's following directory structure:

Expand All @@ -8,7 +8,7 @@ Suppose there's following directory structure:
/another_class.rb # class SomeNamespace:AnotherClass; end
/some_namespace.rb # module SomeNamespace; end

All these classes will be loaded automatically, on demand:
All these classes will be loaded automatically:

``` ruby
require 'class_loader'
Expand All @@ -17,24 +17,32 @@ SomeClass
SomeNamespace::AnotherClass
```

No need for require:
No need for `require` or `autoload`:

``` ruby
require 'some_class'
require 'some_namespace'
require 'some_namespace/another_class'
```

or autoload:

``` ruby
autoload :SomeClass, 'some_class'
autoload :SomeNamespace, 'some_namespace'
module SomeNamespace
autoload :AnotherClass, 'some_namespace/another_class'
end
```

You can also tell it to watch and reload changes:

``` ruby
ClassLoader.watch 'my_app/lib'
```

Or preload classes eagerly:

``` ruby
ClassLoader.preload 'my_app/lib'
```

## Installation

$ gem install class_loader
Expand Down

0 comments on commit 1a9dd98

Please sign in to comment.