0

このRailsCast on Facebook API をフォローしています。次のコードでは、ブロックを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

4

2 に答える 2

1

それは古い質問ですが、私はそれに出くわし、可能な答えを見つけたので、他の誰かが興味を持っている場合に備えてここに残します. これはwebsocket-rubyから来ています。アイデアは、レスキュー ラッパーを使用する場合と使用しない場合の両方でメソッドを提供する一貫した方法を提供することです。

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
于 2016-07-28T16:30:41.497 に答える
1

このために委任を試すことができます

http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/

于 2013-03-06T14:58:58.650 に答える