I am building a sinatra app that will use Highrise CRM gem to access Highrise data. This gem is based on ActiveResource class. I want to set site, user fields for every request. I followed suggestion posted here - Is it thread safe to set Active Resource HTTP authentication on a per-user basis?. I add code (shown below) and I get an error. Can anyone help understand this error and how to fix it.
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
And the error:
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>'
------------------------update-----------------------------
I tried your suggestion, I now get this error.
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'
While defining method with
define_method
you can specify its arguments passing them as arguments to the block and not todefine_method
itself. So you can define setter method like that:I've been playing a lot with setting
site
option dynamically during runtime and the only solution I have found which will not lead to race condition.