如何改进这个 Oauth Rubocop 代码?

How to improve on this Oauth Rubocop code?

我有以下方法设置来帮助刷新 Oauth 令牌:

module WhiplashOmniAuthentication
  extend ActiveSupport::Concern

  module ClassMethods
    def from_omniauth(auth)
      Rails.logger.debug auth.inspect
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
        user.store_token(auth.credentials)
      end
    end
  end

  def refresh_token!
    settings = Devise.omniauth_configs[:whiplash].strategy
    strategy = OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
    client = strategy.client
    access_token = OAuth2::AccessToken.new client, token, refresh_token: refresh_token
    if access_token
      begin
        result = access_token.refresh!
        store_token(result)
        save
      rescue OAuth2::Error => e
        errors[:token] << e.inspect
        return false
      end
    else
      errors[:token] << e.inspect
      return false
    end
  end

  def store_token(auth_token)
    self.token = auth_token.token
    self.refresh_token = auth_token.refresh_token
    self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
  end

  def token_expired?
    Time.now > token_expires_at
  end
end

我试着把它分解成不同的方法,但它一直在爆炸,所以我要在这里听取读者的意见。我正在寻找通过警察和学习的建议。

您在 refresh_token! 实施中肯定有太多事情要做。您总是希望保留方法来做一件事并且只做一件事。它使测试(例如:存根特定方法)、调试和可读性变得更容易。

看看以下是否有帮助:

module WhiplashOmniAuthentication
  extend ActiveSupport::Concern

  module ClassMethods
    def from_omniauth(auth)
      Rails.logger.debug auth.inspect
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
        user.store_token(auth.credentials)
      end
    end
  end

  def refresh_token!
    access_token ? refresh_access_token! : false
  end

  def refresh_access_token!
    result = access_token.refresh!
    store_token(result)
    save
  rescue OAuth2::Error
    false
  end

  def settings
    @settings ||= Devise.omniauth_configs[:whiplash].strategy
  end

  def strategy
    @strategy ||= OmniAuth::Strategies::Whiplash.new(nil, settings.client_id, settings.client_secret, client_options: settings.client_options)
  end

  def client
    @client ||= strategy.client
  end

  def access_token
    OAuth2::AccessToken.new(client, token, refresh_token: refresh_token)
  end

  def store_token(auth_token)
    self.token = auth_token.token
    self.refresh_token = auth_token.refresh_token
    self.token_expires_at = Time.at(auth_token.expires_at).to_datetime
  end

  def token_expired?
    Time.now > token_expires_at
  end
end