我有一個數據庫模型,實際上沒有任何數據,因爲我的所有用戶信息都存儲在第三方認證服務上。我希望能夠像常規一樣使用模型,所以在加載時,我從API獲取所有信息並將其存儲在實例變量中。如何在ActiveModel :: Model中使用before_action類型回調?
如何爲我的模型設置類似回調的before_action
?有沒有Ruby方法來做到這一點?
class Auth0User < ApplicationRecord
before_action set_instance_variables
validates :auth0_id, presence: true,
uniqueness: true
def info(key = nil)
key.nil? ? @user : @user[key.to_s]
end
private
def set_instance_variables
@user ||= auth0_api.user auth0_id
end
def auth0_api
Auth0Client.new(
client_id: Rails.application.secrets.auth0_client_id,
token: Rails.application.secrets.auth0_management_jwt,
domain: Rails.application.secrets.auth0_domain,
api_version: 2
)
end
end
https://dockyard.com/blog/2013/08/20/design-patterns-observer-pattern – max
http://guides.rubyonrails.org/active_record_callbacks.html – steel