Sha256: 9afecfcf9a8a2bda0ff01cd98f0783574260930d9cbf60509d2b5db84201c99b

Contents?: true

Size: 1.11 KB

Versions: 2

Compression:

Stored size: 1.11 KB

Contents

module ApiResponder
  module Formattable
    class UnsupportedVersion < StandardError; end

    module ClassMethods
      def api_formats(*formats)
        @api_formats ||= [ :json ]
        return @api_formats if formats.empty?

        formats.map!(&:to_sym)
        formats -= @api_formats

        formats.each do |format|
          method = :"to_#{format}"
          send :define_method, method do |options|
            as_api(options.merge(:format => format)).send method, options
          end
          @api_formats << format
        end
      end
    end

    module InstanceMethods
      def as_json(options)
        as_api(options.merge(:format => :json)).as_json(options)
      end

      def as_api(options)
        raise UnsupportedVersion.new unless options[:api_version]

        method = :"as_api_v#{options[:api_version]}"
        raise UnsupportedVersion.new unless respond_to? method

        options.delete(:api_version)
        return send method, options
      end
    end

    def self.included(receiver)
      receiver.extend         ClassMethods
      receiver.send :include, InstanceMethods
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
api-responder-1.0.1 lib/api-responder/formattable.rb
api-responder-1.0.0 lib/api-responder/formattable.rb