I've been asked to build a gem out of a number of ActiveResource subclasses in a Rails app of ours.
The difficulty is that the self.site
call uses a constant set in the Rails environment file (so that dev, test, and production point to different websites). After adding my new gem to the Gemfile, I find that the app loads the gem before the environment file, so my ActiveResource models break the app.
What should I do?
Specs: Rails 3.2.3, Ruby 1.9.3
What I ended up doing was overriding self.site
and self.format
and self.connection
, letting them look for the environment constant only the first time the methods are called:
module MyActiveResource
# A flag to indicate whether the environment variable has already been sought
attr_accessor :active_record_fields_set
# Set site & format if not set
def connection(refresh=false)
set_my_active_record_fields unless active_record_fields_set
super(refresh)
end
# Set site & format if not set
def site
set_my_active_record_fields unless active_record_fields_set
super
end
# Set site & format if not set
def format
set_my_active_record_fields unless active_record_fields_set
super
end
# Set site & format
def set_my_active_record_fields
self.active_record_fields_set = true
self.site = MY_CONSTANT
self.format = ActiveResource::Formats::XmlFormat
end
end
Then extend MyActiveResource
in my classes that descend from ActiveResource::Base
.