2

我正在构建一个 sinatra 应用程序,它将使用 Highrise CRM gem 来访问 Highrise 数据。这个 gem 基于 ActiveResource 类。我想为每个请求设置站点、用户字段。我遵循了此处发布的建议-在每个用户的基础上设置活动资源 HTTP 身份验证是否线程安全?. 我添加代码(如下所示),但出现错误。任何人都可以帮助理解这个错误以及如何解决它。

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'
4

2 回答 2

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
于 2012-01-29T13:47:40.063 回答
0

在定义方法时,define_method您可以指定其参数,将它们作为参数传递给块而不是define_method自身。所以你可以像这样定义setter方法:

define_method("#{attr}=") do |val|
  Thread.current["active_resource.#{attr}"] = val
end
于 2011-12-24T08:04:31.753 回答