带 Rails 的动态命名空间 rake 和解析器类?
我有一组解析器,它们在逻辑上有很大不同,但具有完全相同的方法和输出。
我设计了一个大师级的 Rake,我很好奇我的想法是否会导致一些意外或奇怪的行为。
本质上,我的 parse.rake 看起来像这样:
require 'app/models/provider'
require 'config/environment.rb'
Provider.all.each do |provider|
require "lib/tasks/#{provider.name}.rb"
Kernel.const_get(provider.name).provider = provider
namespace provider.name do
task :provider_task do #Parse method
Kernel.const_get(provider.name).provider_task()
end
end
end
由于类是 ruby 中的常量,因此我用来从 varname 访问类方法。我的类看起来像 (ABC.rb
):
Class ABC
cattr_accessor :provider
def self.provider_task()
#Parse and add stuff to environment
end
end
通过此设置,我可以轻松调用 rake ABC:provider_task
来运行特定的解析器。此外,cattr_accessor
允许我轻松引用实际的提供程序模型。想法?
I have a collection of parsers that differ significantly in logic, but have the exact same methods and outputs.
I have devised somewhat of a master Rake
and I am curious if what I have come up with could lead to some unexpected or weird behavior.
Essentially my parse.rake
looks something like:
require 'app/models/provider'
require 'config/environment.rb'
Provider.all.each do |provider|
require "lib/tasks/#{provider.name}.rb"
Kernel.const_get(provider.name).provider = provider
namespace provider.name do
task :provider_task do #Parse method
Kernel.const_get(provider.name).provider_task()
end
end
end
Since classes are constants in ruby, Kernel.const_get
is what I used to access class methods from a varname. My classes look like (ABC.rb
):
Class ABC
cattr_accessor :provider
def self.provider_task()
#Parse and add stuff to environment
end
end
With this setup, I can easily invoke rake ABC:provider_task
to run a specific parser. Also the cattr_accessor
allows me to easily refer to the actual provider model. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经使用它几个星期了,没有任何问题。在与一些同事进行审查后,我发现一些以前使用过类似方法的人没有任何问题。唯一潜在的危险是与您的 ruby 类的命名冲突。
I have used this with no issues for a few weeks. After reviewing with some colleagues, I found a few who previously used a similar approach with no issues. Only potential danger is naming conflicts with your ruby classes.