Modulation - Ruby 的明确依赖管理
Modulation | mɒdjʊˈleɪʃ(ə)n | Music - a change from one key to another in a piece of music.
INSTALL | GUIDE | API | EXAMPLES | RDOC
Modulation provides an alternative way of organizing your Ruby code. Modulation lets you explicitly import and export declarations in order to better control dependencies in your codebase. Modulation helps you refrain from littering the global namespace with a myriad modules, or complex multi-level nested module hierarchies.
Using Modulation, you will always be able to tell where a class or module comes from, and you'll have full control over which parts of a module's code you wish to expose to the outside world. Modulation can also help you write Ruby code in a functional style, minimizing boilerplate code.
Note: Modulation is not a replacement for RubyGems. Rather, Modulation is intended for managing dependencies between source files inside your Ruby applications. Though it does support loading gems that were written using Modulation, it is not intended as a comprehensive solution for using third-party libraries.
You're probably asking yourself "what the ****?" , but when your Ruby app grows
and is split into multiple files loaded using #require, you'll soon hit some
issues:
#required, any class, module or constant in it is available
to any other file in your codebase. All "globals" (classes, modules,
constants) are loaded, well, globally, in a single namespace. Name conflicts
are easy in Ruby.#required class or module can be loaded in any file and then made
available to all files, it's easy to lose track of where it was loaded, and
where it is used.#private, #private_constant etc, but by default everything is
#public!Ruby bug tracker regarding possible solutions to the problem of top-level name collision. Hopefully, the present gem could contribute to an eventual "official" API.
Personally, I have found that managing dependencies with #require in large
codebases is... not as elegant or painfree as I would expect from a
first-class development environment. I also wanted to have a better solution
for writing in a functional style.
So I came up with Modulation, a small gem that takes a different approach to organizing Ruby code: any so-called global declarations are hidden unless explicitly exported, and the global namespace remains clutter-free. All dependencies between source files are explicit, visible, and easy to understand.
You can install the Modulation using gem install, or add it to your Gemfile:
gem 'modulation'Modulation builds on the idea of a Ruby Module as a
"collection of methods and constants".
Using modulation, each Ruby source file becomes a module. Modules usually
export method and constant declarations (usually an API for a specific,
well-defined functionality) to be shared with other modules. Modules can also
import declarations from other modules. Anything not exported remains hidden
inside the module and normally cannot be accessed from the outside.
Each source file is evaluated in the context of a newly-created Module
instance, with some additional methods for introspection and miscellaneous
operations such as hot reloading.
Modulation provides alternative APIs for loading modules. Instead of using
require and require_relative, we use import, import_map etc, discussed
in detail in the API reference.
Any class, module or constant be exported using #export:
export :User, :Session
class User
...
end
class Session
...
endA module may also expose a set of methods without using `class { 'hello' }, MY_CONST: 42 )
def bar :baz end
*app.rb*
```ruby
m = import('./module')
m.foo #=> :baz
m.baz #=> 'hello'
m::MY_CONST #=> 42Any capitalized key will be interpreted as a const, otherwise it will be defined as a method. If the value is a symbol, Modulation will look for the corresponding method or const definition and will treat the key as an alias.
The export method can be called multiple times. Its behavior is additive:
# this:
export :foo, :bar
# is the same as this:
export :foo
export :barDeclarations from another module can be imported using #import:
require 'modulation'
Models = import('./models')
...
user = Models::User.new(...)
...Alternatively, a module interested in a single declaration from another module can use the following technique:
require 'modulation'
User = import('./models')::User
...
user = User.new(...)
…
ruby
Modulation.add_tags(
models: '../lib/models',
views: '../lib/views'
)
...
User = import '@models/user'To load all source files in a directory you can use #import_all:
import_all('./ext')Groups of modules providing a uniform interface can also be loaded using
#import_map:
API = import_map('./math_api') #=> hash mapping filenames to modules
API.keys #=> ['add', 'mul', 'sub', 'div']
API['add'].(2, 2) #=> 4The #import_map takes an optional block to transform hash keys:
API = import_map('./math_api') { |name, mod| name.to_sym }
API.keys #=> [:add, :mul, :sub, :div]
API[:add].(2, 2) #=> 4Modulation provides the #extend_from and #include_from methods to include
imported methods in classes and objects:
module Sequences
extend_from('./seq.rb')
end
Sequences.fib(5)
# extend integers
require 'modulation'
class Integer
include_from('./seq.rb')
def seq(kind)
send(kind, self)
end
end
5.seq(:fib)The #include_from method accepts an optional list of symbols to import:
class Integer
include_from './seq.rb', :fib
end
5.fibA module may wish to expose just a single class or constant, in which case it
can use #export_default:
user.rb
export_default :User
class User
...
endapp.rb
require 'modulation'
User = import('./user')
User.new(...)The default exported value can also be defined directly thus:
config.rb
export_default(
host: 'localhost',
port: 1234,
...
)app.rb
require 'modulation'
config = import('./config')
db.connect(config[:host], config[:port])Circular dependencies, while not the best practice for organizing a code base, are sometimes useful. Modulation supports circular dependencies, with the exception of modules with default exports.
The special constant MODULE allows you to access the containing module from
nested modules or classes. This lets you call methods defined in the module's
root namespace, or otherwise introspect the module:
export :AsyncServer
# Await a promise-like callable
def await
calling_fiber = Fiber.current
p = ->(v = nil) {calling_fiber.resume v}
yield p
Fiber.yield
end
class AsyncServer x, y { x + y },
mul: -> x, y { x * y }
)
m.add(2, 3)
m.mul(2, 3)
# Using a string
m = Modulation.create Lazy-loaded constants must always be qualified. When referring to a
> lazy-loaded constant from the module's top namespace, use the `MODULE`
> namespace, as shown above.
The `#auto_import` method can also take a hash mapping constant names to paths.
This is especially useful when multiple concerns are grouped under a single
namespace:
```ruby
export_default :SuperNet
module SuperNet
auto_import(
HTTP1: './http1',
HTTP2: './http2',
WebSockets: './websockets'
)
end
SuperNet::HTTP1 #=> loads the http1 moduleModules can be reloaded at run-time for easy hot code reloading:
require 'modulation'
SQL = import('./sql')
...
SQL.__reload!Another way to reload modules is using Modulation.reload, which accepts a
module or a filename:
require 'filewatcher'
FileWatcher.new(['lib']).watch do |fn, event|
if(event == :changed)
Modulation.reload(fn)
end
endWhen a module is reloaded, its entire content - constants and methods - will be replaced. That means that any code using that module could continue to use it without even being aware it was reloaded, providing its API has not changed.
Reloading of modules with default exports is also possible. Modulation will
extend the exported value with a #__reload! method. The value will need to be
reassigned:
require 'modulation'
settings = import('settings')
...
settings = settings.__reload!Please note that Modulation does not include a directory watcher that automatically reloads changed modules. This is due to multiple considerations that include the chosen threading model, or the reactor engine in use, or even the chosen solution for watching files (whether it's an external gem or an internal tool).
It is, however, quite trivial to watch files using
directory_watcher:
require 'directory_watcher'
dw = DirectoryWatcher.new 'lib', glob: '**/*.rb', interval: 2, pre_load: true
dw.add_observer do |*events|
events.each do |e|
next unless e.type == :modified
Modulation.reload e.path
end
end
dw.startBefore a module is reloaded, all of its methods and constants are removed. In some cases, a module might need to retain state across reloads. You can do this by simply using instance variables:
export :value, :inc
@counter ||= 0
def value
@counter
end
def incr
@counter += 1
endCare must be taken not to reassign values outside of methods, as this will
overwrite any value retained in the instance variable. To assign initial values,
use the ||= operator as in the example above. See also the
reload example.
Modulation allows runtime introspection of dependencies between modules. You can interrogate a module's dependencies (i.e. the modules it import
暂无开放 Issues,或尚未同步最近议题。