Sha256: a8b24fec8b3788e41e8d1e4434cb0eda5c0134be09e4bfd3a0f1e5e3dd3d2dc6

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

module ActsAsApi

  # The methods of this module are included into the AbstractController::Rendering
  # module.
  module Rendering

    # Provides an alternative to the +render+ method used within the controller
    # to simply generate API outputs.
    #
    # The default Rails serializers are used to serialize the data.
    def render_for_api(render_options)

      # extract the api format and model
      api_format_options = {}

      ActsAsApi::ACCEPTED_API_FORMATS.each do |item|
        if render_options.has_key?(item)
          api_format_options[item] = render_options[item]
          render_options.delete item
        end
      end


      api_format =  api_format_options.keys.first
      api_model =  api_format_options.values.first

      # set the params to render
      output_params = render_options


      # set the name of the root node - pluralize for arrays
      if api_model.is_a?(Array)
        api_root_name = api_model.respond_to?(:model_name) ? api_model.model_name.singular.pluralize :  api_model.first.class.model_name.singular.pluralize
      else
        api_root_name = api_model.class.model_name.singular
      end

      api_root_name.dasherize if api_format.to_s == :xml.to_s

      # Does not work
      #api_root_name.camelize if api_format.to_s == :json.to_s

      output_params[:root] ||= api_root_name

      

      #output_params[:root] = output_params[:root].camelize if render_options.has_key?(:camelize) && render_options[:camelize]
      #output_params[:root] = output_params[:root].dasherize if !render_options.has_key?(:dasherize) || render_options[:dasherize]


      api_response = api_model.as_api_response

      if ActsAsApi::ADD_ROOT_NODE_FOR.include? api_format
        api_response = { api_root_name.to_sym =>  api_response}
      end


      # create the Hash as response
      output_params[api_format] = api_response

      render output_params

    end

  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_api-0.1.7 lib/acts_as_api/rendering.rb