Ruby on rails 使用Rails中的rescue自动环绕方法

Ruby on rails 使用Rails中的rescue自动环绕方法,ruby-on-rails,Ruby On Rails,我正在关注这一点。下面的代码允许将块传递到facebook方法,并从rescue中获益 def facebook @facebook ||= Koala::Facebook::API.new(oauth_token) block_given? ? yield(@facebook) : @facebook rescue Koala::Facebook::APIError => e logger.info e.to_s nil # or con

我正在关注这一点。下面的代码允许将块传递到
facebook
方法,并从
rescue
中获益

  def facebook
     @facebook ||= Koala::Facebook::API.new(oauth_token)
     block_given? ? yield(@facebook) : @facebook
   rescue Koala::Facebook::APIError => e
     logger.info e.to_s
     nil # or consider a custom null object
   end

   def friends_count
     facebook { |fb| fb.get_connection("me", "friends").size }
   end
然而,我有十几个方法调用这里定义的
facebook
方法,我不想在每个方法中重复
facebook{}
。(语法不是特别好)


有没有办法简化这一点?类似于一个过滤器,它将环绕调用
facebook
的每个方法

您可以为此尝试委派


这是一个较老的问题,但我只是偶然发现了它和一个可能的答案,所以我将把它留在这里,以防其他人感兴趣。它来自中国。我们的想法是提供一种一致的方式来提供方法,无论有没有援救包装都可以让您享受

module WebSocket
  module ExceptionHandler
    attr_accessor :error

    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      # Rescue from WebSocket::Error errors.
      #
      # @param [String] method_name Name of method that should be wrapped and rescued
      # @param [Hash] options Options for rescue
      #
      # @options options [Any] :return Value that should be returned instead of raised error
      def rescue_method(method_name, options = {})
        define_method "#{method_name}_with_rescue" do |*args|
          begin
            send("#{method_name}_without_rescue", *args)
          rescue WebSocket::Error => e
            self.error = e.message.to_sym
            WebSocket.should_raise ? raise : options[:return]
          end
        end
        alias_method "#{method_name}_without_rescue", method_name
        alias_method method_name, "#{method_name}_with_rescue"
      end
    end
  end
end

你的代码是明确的,我会保留it@apneadiving谢谢这很有道理。谢谢你的回答。您能详细说明我如何在这种情况下使用委托吗?我读了这篇博文,但仍然不太清楚如何去做。我很好奇在这种情况下会看到委托。我的想法是,你可以在函数调用中委托给@facebook实例,但我想如果你没有捕捉到异常,那么你会有问题。我还对“一个领先者”的评论投了赞成票。我想你应该把代码保持原样。