I have a database model that doesn't actually have any data since all my User information is stored on a third party authentication service. I want to be able to use the Model like a regular one, so upon load, I fetch all the information from the API and store it in an instance variable.
How do I setup a before_action
like callback for my model? Is there a Ruby way to do this?
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
after_intialize
完全符合我的需要。
Yes, and actually rails had a lot of methods for you to choose:
You can check here for more methods: http://guides.rubyonrails.org/active_record_callbacks.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.