Skip to content

Instantly share code, notes, and snippets.

@chsh
Last active March 6, 2018 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chsh/1efe96ae11f535b82e877f7790e3e0da to your computer and use it in GitHub Desktop.
Save chsh/1efe96ae11f535b82e877f7790e3e0da to your computer and use it in GitHub Desktop.
Allow to refer user related info using thread global `Current` (like CurrentAttributes in Rails 5.2 ;-)
class Current
class Default
def self.user; nil end
def self.admin?; false end
def self.country
@country ||= Rails.configuration.x.default.user_country
end
def self.currency
@currency ||= Rails.configuration.x.default.user_currency
end
def self.timezone
@timezone ||= Time.zone_default
end
end
def self.default; Default end
include RequestStoreDefiner
request_store_accessor :user, :country, :currency, :admin?, :timezone
def self.for(user)
if user.present?
self.user = user
self.admin = user.admin?
self.currency = user.currency || default.currency
self.country = user.country || default.country
self.timezone = user.timezone.present? ? Time.find_zone!(user.timezone) : default.timezone
end
self
end
def self.now
self.timezone.now
end
end
gem 'request_store'
module RequestStoreDefiner
extend ActiveSupport::Concern
class_methods do
def request_store_reader(*methods)
methods = [methods].flatten
methods.each do |method|
if method.to_s.last == '?'
m = method.to_s.chop.to_sym
else
m = method
end
define_singleton_method method do
RequestStore.store[m] || default.send(method)
end
end
end
def request_store_writer(*methods)
methods = [methods].flatten
methods.each do |method|
if method.to_s.last == '?'
m = method.to_s.chop.to_sym
define_singleton_method "#{m}=" do |value|
RequestStore.store[m] = value ? true : false
end
else
define_singleton_method "#{method}=" do |value|
RequestStore.store[method] = value
end
end
end
end
def request_store_accessor(*methods)
request_store_reader(*methods)
request_store_writer(*methods)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment