+
+ def act_as_user user
+ user_was = Thread.current[:user]
+ Thread.current[:user] = user
+ begin
+ yield
+ ensure
+ Thread.current[:user] = user_was
+ end
+ end
+
+ def anonymous_group
+ $anonymous_group = check_cache $anonymous_group do
+ act_as_system_user do
+ ActiveRecord::Base.transaction do
+ Group.where(uuid: anonymous_group_uuid).
+ first_or_create!(group_class: "role",
+ name: "Anonymous users",
+ description: "Anonymous users")
+ end
+ end
+ end
+ end
+
+ def anonymous_user
+ $anonymous_user = check_cache $anonymous_user do
+ act_as_system_user do
+ User.where(uuid: anonymous_user_uuid).
+ first_or_create!(is_active: false,
+ is_admin: false,
+ email: 'anonymous',
+ first_name: 'Anonymous',
+ last_name: '') do |u|
+ u.save!
+ Link.where(tail_uuid: anonymous_user_uuid,
+ head_uuid: anonymous_group.uuid,
+ link_class: 'permission',
+ name: 'can_read').
+ first_or_create!
+ end
+ end
+ end
+ end
+
+ def empty_collection_uuid
+ 'd41d8cd98f00b204e9800998ecf8427e+0'
+ end
+
+ def empty_collection
+ $empty_collection = check_cache $empty_collection do
+ act_as_system_user do
+ ActiveRecord::Base.transaction do
+ Collection.
+ where(portable_data_hash: empty_collection_uuid).
+ first_or_create!(manifest_text: '', owner_uuid: anonymous_group.uuid)
+ end
+ end
+ end
+ end
+
+ private
+
+ # If the given value is nil, or the cache has been cleared since it
+ # was set, yield. Otherwise, return the given value.
+ def check_cache value
+ if not Rails.env.test? and
+ ActionController::Base.cache_store.is_a? ActiveSupport::Cache::FileStore and
+ not File.owned? ActionController::Base.cache_store.cache_path
+ # If we don't own the cache dir, we're probably
+ # crunch-dispatch. Whoever we are, using this cache is likely to
+ # either fail or screw up the cache for someone else. So we'll
+ # just assume the $globals are OK to live forever.
+ #
+ # The reason for making the globals expire with the cache in the
+ # first place is to avoid leaking state between test cases: in
+ # production, we don't expect the database seeds to ever go away
+ # even when the cache is cleared, so there's no particular
+ # reason to expire our global variables.
+ else
+ Rails.cache.fetch "CurrentApiClient.$globals" do
+ value = nil
+ true
+ end
+ end
+ return value unless value.nil?
+ yield
+ end