我正在构建一个sinatra应用程序,它将使用Highrise CRM gem访问Highrise数据。这个gem基于ActiveResource类。我想为每个请求设置站点,用户字段。我按照这里发布的建议 - Is it thread safe to set Active Resource HTTP authentication on a per-user basis?。我添加代码(如下所示),我收到一个错误。任何人都可以帮助理解此错误以及如何解决它。
class ActiveResource::Base
class << self
%w(site user).each do |attr|
define_method(attr) do
Thread.current["active_resource.#{attr}"]
end
define_method("#{attr}=", val) do
Thread.current["active_resource.#{attr}"] = val
end
end
end
end
错误:
c:/dev/hgadget/application.rb:18:in `block in singletonclass':
undefined local variable or method `val' for #<Class:ActiveResource::Base> (NameError)
from c:/dev/hgadget/application.rb:12:in `each'
from c:/dev/hgadget/application.rb:12:in `singletonclass'
from c:/dev/hgadget/application.rb:11:in `<class:Base>'
from c:/dev/hgadget/application.rb:9:in `<top (required)>'
from <internal:lib/rubygems/custom_require>:29:in `require'
from <internal:lib/rubygems/custom_require>:29:in `require'
from application_test.rb:1:in `<main>'
------------------------更新---------------------- -------
我尝试了你的建议,我现在收到了这个错误。
NoMethodError - undefined method `path' for "https://test.abcd.com":String:
c:/Ruby192/lib/ruby/gems/1.9.1/gems/activeresource3.0.11/lib/active_resource/base.rb:562:in `prefix'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/activeresource3.0.11/lib/active_resource/base.rb:667:in `collection_path'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/activeresource3.0.11/lib/active_resource/base.rb:856:in `find_every'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/activeresource-3.0.11/lib/active_resource/base.rb:777:in `find' application.rb:78:in `block in <main>'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:1212:in `call'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:1212:in `block in compile!'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:772:in `[]'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:772:in `block (3 levels) in route!'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:788:in `route_eval'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:772:in `block (2 levels) in route!'
c:/Ruby192/lib/ruby/gems/1.9.1/gems/sinatra-1.3.1/lib/sinatra/base.rb:821:in `block in process_route'
答案 0 :(得分:1)
我在运行时动态设置site
选项并且找到了唯一不会导致竞争条件的解决方案,我一直在玩很多。
class Runner
def self.new(site)
Class.new(ActiveResource::Base) do
self.site = site
self.element_name = 'runner'
# your methods here
end.new
end
end
答案 1 :(得分:0)
在使用define_method
定义方法时,您可以指定其参数,将它们作为参数传递给块,而不是define_method
本身。所以你可以像这样定义setter方法:
define_method("#{attr}=") do |val|
Thread.current["active_resource.#{attr}"] = val
end