--- /dev/null
+Copyright (c) 2012 Santiago Pastorino and Carlos Antonio da Silva
+
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--- /dev/null
+# Rails::API
+
+[](http://travis-ci.org/rails-api/rails-api)
+
+**Rails::API** is a subset of a normal Rails application, created for applications that don't require all functionality that a complete Rails application provides. It is a bit more lightweight, and consequently a bit faster than a normal Rails application. The main example for its usage is in API applications only, where you usually don't need the entire Rails middleware stack nor template generation.
+
+## Using Rails for API-only Apps
+
+This is a quick walk-through to help you get up and running with **Rails::API** to create API-only Apps, covering:
+
+* What **Rails::API** provides for API-only applications
+* How to decide which middlewares you will want to include
+* How to decide which modules to use in your controller
+
+### What is an API app?
+
+Traditionally, when people said that they used Rails as an "API", they meant providing a programmatically accessible API alongside their web application.
+For example, GitHub provides [an API](http://developer.github.com) that you can use from your own custom clients.
+
+With the advent of client-side frameworks, more developers are using Rails to build a backend that is shared between their web application and other native applications.
+
+For example, Twitter uses its [public API](https://dev.twitter.com) in its web application, which is built as a static site that consumes JSON resources.
+
+Instead of using Rails to generate dynamic HTML that will communicate with the server through forms and links, many developers are treating their web application as just another client, consuming a simple JSON API.
+
+This guide covers building a Rails application that serves JSON resources to an API client *or* client-side framework.
+
+### Why use Rails for JSON APIs?
+
+The first question a lot of people have when thinking about building a JSON API using Rails is: "isn't using Rails to spit out some JSON overkill? Shouldn't I just use something like Sinatra?"
+
+For very simple APIs, this may be true. However, even in very HTML-heavy applications, most of an application's logic is actually outside of the view layer.
+
+The reason most people use Rails is that it provides a set of defaults that allows us to get up and running quickly without having to make a lot of trivial decisions.
+
+Let's take a look at some of the things that Rails provides out of the box that are still applicable to API applications.
+
+#### Handled at the middleware layer:
+
+* Reloading: Rails applications support transparent reloading. This works even if your application gets big and restarting the server for every request becomes non-viable.
+* Development Mode: Rails application come with smart defaults for development, making development pleasant without compromising production-time performance.
+* Test Mode: Ditto test mode.
+* Logging: Rails applications log every request, with a level of verbosity appropriate for the current mode. Rails logs in development include information about the request environment, database queries, and basic performance information.
+* Security: Rails detects and thwarts [IP spoofing attacks](http://en.wikipedia.org/wiki/IP_address_spoofing) and handles cryptographic signatures in a [timing attack](http://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what an IP spoofing attack or a timing attack is? Exactly.
+* Parameter Parsing: Want to specify your parameters as JSON instead of as a URL-encoded String? No problem. Rails will decode the JSON for you and make it available in *params*. Want to use nested URL-encoded params? That works too.
+* Conditional GETs: Rails handles conditional *GET*, (*ETag* and *Last-Modified*), processing request headers and returning the correct response headers and status code. All you need to do is use the [*stale?*](http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F) check in your controller, and Rails will handle all of the HTTP details for you.
+* Caching: If you use *dirty?* with public cache control, Rails will automatically cache your responses. You can easily configure the cache store.
+* HEAD requests: Rails will transparently convert *HEAD* requests into *GET* requests, and return just the headers on the way out. This makes *HEAD* work reliably in all Rails APIs.
+
+While you could obviously build these up in terms of existing Rack middlewares, I think this list demonstrates that the default Rails middleware stack provides a lot of value, even if you're "just generating JSON".
+
+#### Handled at the ActionPack layer:
+
+* Resourceful Routing: If you're building a RESTful JSON API, you want to be using the Rails router. Clean and conventional mapping from HTTP to controllers means not having to spend time thinking about how to model your API in terms of HTTP.
+* URL Generation: The flip side of routing is URL generation. A good API based on HTTP includes URLs (see [the GitHub gist API](http://developer.github.com/v3/gists/) for an example).
+* Header and Redirection Responses: `head :no_content` and `redirect_to user_url(current_user)` come in handy. Sure, you could manually add the response headers, but why?
+* Basic, Digest and Token Authentication: Rails comes with out-of-the-box support for three kinds of HTTP authentication.
+* Instrumentation: Rails 3.0 added an instrumentation API that will trigger registered handlers for a variety of events, such as action processing, sending a file or data, redirection, and database queries. The payload of each event comes with relevant information (for the action processing event, the payload includes the controller, action, params, request format, request method and the request's full path).
+* Generators: This may be passé for advanced Rails users, but it can be nice to generate a resource and get your model, controller, test stubs, and routes created for you in a single command.
+* Plugins: Many third-party libraries come with support for Rails that reduces or eliminates the cost of setting up and gluing together the library and the web framework. This includes things like overriding default generators, adding rake tasks, and honoring Rails choices (like the logger and cache backend).
+
+Of course, the Rails boot process also glues together all registered components. For example, the Rails boot process is what uses your *config/database.yml* file when configuring ActiveRecord.
+
+**The short version is**: you may not have thought about which parts of Rails are still applicable even if you remove the view layer, but the answer turns out to be "most of it".
+
+### The Basic Configuration
+
+If you're building a Rails application that will be an API server first and foremost, you can start with a more limited subset of Rails and add in features as needed.
+
+**NOTE**: rails-api only supports Ruby 1.9.3 and above.
+
+#### For new apps
+
+Install the gem if you haven't already:
+
+ gem install rails-api
+
+Then generate a new **Rails::API** app:
+
+ rails-api new my_api
+
+This will do two main things for you:
+
+* Make *ApplicationController* inherit from *ActionController::API* instead of *ActionController::Base*. As with middleware, this will leave out any *ActionController* modules that provide functionality primarily used by browser applications.
+* Configure the generators to skip generating views, helpers and assets when you generate a new resource.
+
+Rails includes all of the sub-frameworks (ActiveRecord, ActionMailer, etc) by default. Some API projects won't need them all, so at the top of config/application.rb, you can replace `require 'rails/all'` with specific sub-frameworks:
+
+ # config/application.rb
+ # require "active_record/railtie"
+ require "action_controller/railtie"
+ require "action_mailer/railtie"
+ # require "sprockets/railtie"
+ require "rails/test_unit/railtie"
+
+This can also be achieved with flags when creating a new **Rails::API** app:
+
+ rails-api new my_api --skip-active-record --skip-sprockets
+
+Note: There are references to ActionMailer and ActiveRecord in the various
+ config/environment files. If you decide to exclude any of these from your project
+ its best to comment these out in case you need them later.
+
+ # comment out this in config/environments/development.rb
+ config.active_record.migration_error = :page_load
+ config.action_mailer.raise_delivery_errors = false
+
+ # comment out this in config/environments/test.rb
+ config.action_mailer.delivery_method = :test
+
+
+#### For already existing apps
+
+If you want to take an existing app and make it a **Rails::API** app, you'll have to do some quick setup manually.
+
+Add the gem to your *Gemfile*:
+
+ gem 'rails-api'
+
+And run `bundle` to install the gem.
+
+Change *app/controllers/application_controller.rb*:
+
+```ruby
+# instead of
+class ApplicationController < ActionController::Base
+end
+
+# do
+class ApplicationController < ActionController::API
+end
+```
+
+And comment out the `protect_from_forgery` call if you are using it.
+
+If you want to use the Rails default middleware stack (avoid the reduction that rails-api does), you can just add config.api_only = false to config/application.rb file.
+
+### Serialization
+
+We suggest using [ActiveModel::Serializers][ams] to serialize your ActiveModel/ActiveRecord objects into the desired response format (e.g. JSON).
+
+### Choosing Middlewares
+
+An API application comes with the following middlewares by default.
+
+* *ActionDispatch::DebugExceptions*: Log exceptions.
+* *ActionDispatch::Head*: Dispatch *HEAD* requests as *GET* requests, and return only the status code and headers.
+* *ActionDispatch::ParamsParser*: Parse XML, YAML and JSON parameters when the request's *Content-Type* is one of those.
+* *ActionDispatch::Reloader*: In development mode, support code reloading.
+* *ActionDispatch::RemoteIp*: Protect against IP spoofing attacks.
+* *ActionDispatch::RequestId*: Makes a unique request id available, sending the id to the client via the X-Request-Id header. The unique request id can be used to trace a request end-to-end and would typically end up being part of log files from multiple pieces of the stack.
+* *ActionDispatch::ShowExceptions*: Rescue exceptions and re-dispatch them to an exception handling application.
+* *Rack::Cache*: Caches responses with public *Cache-Control* headers using HTTP caching semantics.
+* *Rack::ConditionalGet*: Supports the `stale?` feature in Rails controllers.
+* *Rack::ETag*: Automatically set an *ETag* on all string responses. This means that if the same response is returned from a controller for the same URL, the server will return a *304 Not Modified*, even if no additional caching steps are taken. This is primarily a client-side optimization; it reduces bandwidth costs but not server processing time.
+* *Rack::Lock*: If your application is not marked as threadsafe (`config.threadsafe!`), this middleware will add a mutex around your requests.
+* *Rack::Runtime*: Adds a header to the response listing the total runtime of the request.
+* *Rack::Sendfile*: Uses a front-end server's file serving support from your Rails application.
+* *Rails::Rack::Logger*: Log the request started and flush all loggers after it.
+
+Other plugins, including *ActiveRecord*, may add additional middlewares. In general, these middlewares are agnostic to the type of app you are building, and make sense in an API-only Rails application.
+
+You can get a list of all middlewares in your application via:
+
+ rake middleware
+
+#### Other Middlewares
+
+Rails ships with a number of other middlewares that you might want to use in an API app, especially if one of your API clients is the browser:
+
+* *Rack::MethodOverride*: Allows the use of the *_method* hack to route POST requests to other verbs.
+* *ActionDispatch::Cookies*: Supports the *cookie* method in *ActionController*, including support for signed and encrypted cookies.
+* *ActionDispatch::Flash*: Supports the *flash* mechanism in *ActionController*.
+* *ActionDispatch::BestStandards*: Tells Internet Explorer to use the most standards-compliant available renderer. In production mode, if ChromeFrame is available, use ChromeFrame.
+* Session Management: If a *config.session_store* is supplied and *config.api_only = false*, this middleware makes the session available as the *session* method in *ActionController*.
+
+Any of these middlewares can be added via:
+
+```ruby
+config.middleware.use Rack::MethodOverride
+```
+
+#### Removing Middlewares
+
+If you don't want to use a middleware that is included by default in the API middleware set, you can remove it using *config.middleware.delete*:
+
+```ruby
+config.middleware.delete ::Rack::Sendfile
+```
+
+Keep in mind that removing these features may remove support for certain features in *ActionController*.
+
+### Choosing Controller Modules
+
+An API application (using *ActionController::API*) comes with the following controller modules by default:
+
+* *ActionController::UrlFor*: Makes *url_for* and friends available
+* *ActionController::Redirecting*: Support for *redirect_to*
+* *ActionController::Rendering*: Basic support for rendering
+* *ActionController::Renderers::All*: Support for *render :json* and friends
+* *ActionController::ConditionalGet*: Support for *stale?*
+* *ActionController::ForceSSL*: Support for *force_ssl*
+* *ActionController::RackDelegation*: Support for the *request* and *response* methods returning *ActionDispatch::Request* and *ActionDispatch::Response* objects.
+* *ActionController::DataStreaming*: Support for *send_file* and *send_data*
+* *AbstractController::Callbacks*: Support for *before_filter* and friends
+* *ActionController::Instrumentation*: Support for the instrumentation hooks defined by *ActionController* (see [the source](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/instrumentation.rb) for more).
+* *ActionController::Rescue*: Support for *rescue_from*.
+
+Other plugins may add additional modules. You can get a list of all modules included into *ActionController::API* in the rails console:
+
+```ruby
+ActionController::API.ancestors - ActionController::Metal.ancestors
+```
+
+#### Adding Other Modules
+
+All Action Controller modules know about their dependent modules, so you can feel free to include any modules into your controllers, and all dependencies will be included and set up as well.
+
+Some common modules you might want to add:
+
+* *AbstractController::Translation*: Support for the *l* and *t* localization and translation methods. These delegate to *I18n.translate* and *I18n.localize*.
+* *ActionController::HttpAuthentication::Basic::ControllerMethods* (or *Digest* or *Token*): Support for basic, digest or token HTTP authentication.
+* *AbstractController::Layouts*: Support for layouts when rendering.
+* *ActionController::MimeResponds* (and *ActionController::ImplicitRender* for Rails 4): Support for content negotiation (*respond_to*, *respond_with*).
+* *ActionController::Cookies*: Support for *cookies*, which includes support for signed and encrypted cookies. This requires the cookie middleware.
+
+The best place to add a module is in your *ApplicationController*. You can also add modules to individual controllers.
+
+## Contributing
+
+1. Fork it
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Commit your changes (`git commit -am 'Added some feature'`)
+4. Push to the branch (`git push origin my-new-feature`)
+5. Create new Pull Request
+
+## Maintainers
+
+* Santiago Pastorino (https://github.com/spastorino)
+* Carlos Antonio da Silva (https://github.com/carlosantoniodasilva)
+* Steve Klabnik (https://github.com/steveklabnik)
+
+## License
+
+MIT License.
+
+## Mailing List
+
+https://groups.google.com/forum/?fromgroups#!forum/rails-api-core
+
+[ams]: https://github.com/rails-api/active_model_serializers
--- /dev/null
+#!/usr/bin/env ruby
+
+require 'rails-api/generators/rails/app/app_generator'
+require 'rails/cli'
--- /dev/null
+ruby-rails-api (0.2.0-1) UNRELEASED; urgency=medium
+
+ * Initial release (Closes: #nnnn)
+
+ -- MAINTAINER <valtri@myriad14.zcu.cz> Tue, 11 Mar 2014 22:36:51 +0100
--- /dev/null
+Source: ruby-rails-api
+Section: ruby
+Priority: optional
+Maintainer: Debian Ruby Extras Maintainers <pkg-ruby-extras-maintainers@lists.alioth.debian.org>
+Uploaders: <>
+Build-Depends: debhelper (>= 7.0.50~), gem2deb (>= 0.6.1~)
+Standards-Version: 3.9.4
+#Vcs-Git: git://anonscm.debian.org/pkg-ruby-extras/ruby-rails-api.git
+#Vcs-Browser: http://anonscm.debian.org/gitweb/?p=pkg-ruby-extras/ruby-rails-api.git;a=summary
+Homepage: https://github.com/rails-api/rails-api
+XS-Ruby-Versions: all
+
+Package: ruby-rails-api
+Architecture: all
+XB-Ruby-Versions: ${ruby:Versions}
+Depends: ${shlibs:Depends}, ${misc:Depends}, ruby | ruby-interpreter
+# actionpack (>= 3.2.11), railties (>= 3.2.11), rails (>= 3.2.11, development)
+Description: Rails for API only Applications
+ Rails::API is a subset of a normal Rails application,
+ created for applications that don't require all
+ functionality that a complete Rails application provides
--- /dev/null
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: rails-api
+Source: FIXME <http://example.com/>
+
+Files: *
+Copyright: <years> <put author's name and email here>
+ <years> <likewise for another author>
+License: GPL-2+ (FIXME)
+
+Files: debian/*
+Copyright: 2014 <>
+License: GPL-2+ (FIXME)
+Comment: the Debian packaging is licensed under the same terms as the original package.
+
+License: GPL-2+ (FIXME)
+ This program is free software; you can redistribute it
+ and/or modify it under the terms of the GNU General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later
+ version.
+ .
+ This program is distributed in the hope that it will be
+ useful, but WITHOUT ANY WARRANTY; without even the implied
+ warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ PURPOSE. See the GNU General Public License for more
+ details.
+ .
+ You should have received a copy of the GNU General Public
+ License along with this package; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+ Boston, MA 02110-1301 USA
+ .
+ On Debian systems, the full text of the GNU General Public
+ License version 2 can be found in the file
+ `/usr/share/common-licenses/GPL-2'.
--- /dev/null
+# FIXME: READMEs found
+# README.md
--- /dev/null
+---
+- test/api_application/api_application_test.rb
+- test/api_controller/action_methods_test.rb
+- test/api_controller/conditional_get_test.rb
+- test/api_controller/data_streaming_test.rb
+- test/api_controller/force_ssl_test.rb
+- test/api_controller/redirect_to_test.rb
+- test/api_controller/renderers_test.rb
+- test/api_controller/url_for_test.rb
+- test/generators/app_generator_test.rb
+- test/generators/fixtures/routes.rb
+- test/generators/generators_test_helper.rb
+- test/generators/resource_generator_test.rb
+- test/generators/scaffold_generator_test.rb
+- test/test_helper.rb
--- /dev/null
+#!/usr/bin/make -f
+#export DH_VERBOSE=1
+#
+# Uncomment to ignore all test failures (but the tests will run anyway)
+#export DH_RUBY_IGNORE_TESTS=all
+#
+# Uncomment to ignore some test failures (but the tests will run anyway).
+# Valid values:
+#export DH_RUBY_IGNORE_TESTS=ruby1.9.1 ruby2.0 require-rubygems
+#
+# If you need to specify the .gemspec (eg there is more than one)
+#export DH_RUBY_GEMSPEC=gem.gemspec
+
+%:
+ dh $@ --buildsystem=ruby --with ruby
--- /dev/null
+3.0 (quilt)
--- /dev/null
+version=3
+http://pkg-ruby-extras.alioth.debian.org/cgi-bin/gemwatch/rails-api .*/rails-api-(.*).tar.gz
--- /dev/null
+require 'rails/generators/rails/resource_route/resource_route_generator'
+
+module Rails
+ module Generators
+ class ApiResourceRouteGenerator < ResourceRouteGenerator
+ def add_resource_route
+ return if options[:actions].present?
+ route_config = regular_class_path.collect{ |namespace| "namespace :#{namespace} do " }.join(" ")
+ route_config << "resources :#{file_name.pluralize}"
+ route_config << ", except: [:new, :edit]"
+ route_config << " end" * regular_class_path.size
+ route route_config
+ end
+ end
+ end
+end
--- /dev/null
+require 'rails-api/version'
+require 'rails-api/action_controller/api'
+require 'rails-api/application'
+
+module Rails
+ module API
+ def self.rails4?
+ Rails::VERSION::MAJOR == 4
+ end
+ end
+end
--- /dev/null
+require 'action_view'
+require 'action_controller'
+require 'action_controller/log_subscriber'
+
+module ActionController
+ # API Controller is a lightweight version of <tt>ActionController::Base</tt>,
+ # created for applications that don't require all functionality that a complete
+ # \Rails controller provides, allowing you to create faster controllers for
+ # example for API only applications.
+ #
+ # An API Controller is different from a normal controller in the sense that
+ # by default it doesn't include a number of features that are usually required
+ # by browser access only: layouts and templates rendering, cookies, sessions,
+ # flash, assets, and so on. This makes the entire controller stack thinner and
+ # faster, suitable for API applications. It doesn't mean you won't have such
+ # features if you need them: they're all available for you to include in
+ # your application, they're just not part of the default API Controller stack.
+ #
+ # By default, only the ApplicationController in a \Rails application inherits
+ # from <tt>ActionController::API</tt>. All other controllers in turn inherit
+ # from ApplicationController.
+ #
+ # A sample controller could look like this:
+ #
+ # class PostsController < ApplicationController
+ # def index
+ # @posts = Post.all
+ # render json: @posts
+ # end
+ # end
+ #
+ # Request, response and parameters objects all work the exact same way as
+ # <tt>ActionController::Base</tt>.
+ #
+ # == Renders
+ #
+ # The default API Controller stack includes all renderers, which means you
+ # can use <tt>render :json</tt> and brothers freely in your controllers. Keep
+ # in mind that templates are not going to be rendered, so you need to ensure
+ # your controller is calling either <tt>render</tt> or <tt>redirect</tt> in
+ # all actions.
+ #
+ # def show
+ # @post = Post.find(params[:id])
+ # render json: @post
+ # end
+ #
+ # == Redirects
+ #
+ # Redirects are used to move from one action to another. You can use the
+ # <tt>redirect</tt> method in your controllers in the same way as
+ # <tt>ActionController::Base</tt>. For example:
+ #
+ # def create
+ # redirect_to root_url and return if not_authorized?
+ # # do stuff here
+ # end
+ #
+ # == Adding new behavior
+ #
+ # In some scenarios you may want to add back some functionality provided by
+ # <tt>ActionController::Base</tt> that is not present by default in
+ # <tt>ActionController::API</tt>, for instance <tt>MimeResponds</tt>. This
+ # module gives you the <tt>respond_to</tt> and <tt>respond_with</tt> methods.
+ # Adding it is quite simple, you just need to include the module in a specific
+ # controller or in <tt>ApplicationController</tt> in case you want it
+ # available to your entire app:
+ #
+ # class ApplicationController < ActionController::API
+ # include ActionController::MimeResponds
+ # end
+ #
+ # class PostsController < ApplicationController
+ # respond_to :json, :xml
+ #
+ # def index
+ # @posts = Post.all
+ # respond_with @posts
+ # end
+ # end
+ #
+ # Quite straightforward. Make sure to check <tt>ActionController::Base</tt>
+ # available modules if you want to include any other functionality that is
+ # not provided by <tt>ActionController::API</tt> out of the box.
+ class API < Metal
+ abstract!
+
+ module Compatibility
+ def cache_store; end
+ def cache_store=(*); end
+ def assets_dir=(*); end
+ def javascripts_dir=(*); end
+ def stylesheets_dir=(*); end
+ def page_cache_directory=(*); end
+ def asset_path=(*); end
+ def asset_host=(*); end
+ def relative_url_root=(*); end
+ def perform_caching=(*); end
+ def helpers_path=(*); end
+ def allow_forgery_protection=(*); end
+ def helper_method(*); end
+ def helper(*); end
+ end
+
+ extend Compatibility
+
+ # Shortcut helper that returns all the ActionController::API modules except the ones passed in the argument:
+ #
+ # class MetalController
+ # ActionController::API.without_modules(:Redirecting, :DataStreaming).each do |left|
+ # include left
+ # end
+ # end
+ #
+ # This gives better control over what you want to exclude and makes it easier
+ # to create an api controller class, instead of listing the modules required manually.
+ def self.without_modules(*modules)
+ modules = modules.map do |m|
+ m.is_a?(Symbol) ? ActionController.const_get(m) : m
+ end
+
+ MODULES - modules
+ end
+
+ MODULES = [
+ HideActions,
+ UrlFor,
+ Redirecting,
+ Rendering,
+ Renderers::All,
+ ConditionalGet,
+ RackDelegation,
+
+ ForceSSL,
+ DataStreaming,
+
+ # Before callbacks should also be executed the earliest as possible, so
+ # also include them at the bottom.
+ AbstractController::Callbacks,
+
+ # Append rescue at the bottom to wrap as much as possible.
+ Rescue,
+
+ # Add instrumentations hooks at the bottom, to ensure they instrument
+ # all the methods properly.
+ Instrumentation
+ ]
+
+ if Rails::VERSION::MAJOR >= 4 && Rails::VERSION::MINOR > 0
+ include AbstractController::Rendering
+ include ActionView::Rendering
+ end
+
+ MODULES.each do |mod|
+ include mod
+ end
+
+ if Rails::VERSION::MAJOR >= 4
+ include StrongParameters
+ end
+
+ ActiveSupport.run_load_hooks(:action_controller, self)
+ end
+end
--- /dev/null
+require 'rails/version'
+require 'rails/application'
+require 'rails-api/public_exceptions'
+require 'rails-api/application/default_rails_four_middleware_stack'
+
+module Rails
+ class Application < Engine
+ def default_middleware_stack
+ if Rails::API.rails4?
+ DefaultRailsFourMiddlewareStack.new(self, config, paths).build_stack
+ else
+ rails_three_stack
+ end
+ end
+
+ private
+
+ def setup_generators!
+ generators = config.generators
+
+ generators.templates.unshift File::expand_path('../templates', __FILE__)
+ generators.resource_route = :api_resource_route
+
+ generators.hide_namespace "css"
+
+ generators.rails({
+ :helper => false,
+ :assets => false,
+ :stylesheets => false,
+ :stylesheet_engine => nil,
+ :template_engine => nil
+ })
+ end
+
+ ActiveSupport.on_load(:before_configuration) do
+ config.api_only = true
+ setup_generators!
+ end
+
+ def rails_three_stack
+ ActionDispatch::MiddlewareStack.new.tap do |middleware|
+ if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
+ require "action_dispatch/http/rack_cache"
+ middleware.use ::Rack::Cache, rack_cache
+ end
+
+ if config.force_ssl
+ require "rack/ssl"
+ middleware.use ::Rack::SSL, config.ssl_options
+ end
+
+ if config.action_dispatch.x_sendfile_header.present?
+ middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
+ end
+
+ if config.serve_static_assets
+ middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
+ end
+
+ middleware.use ::Rack::Lock unless config.allow_concurrency
+ middleware.use ::Rack::Runtime
+ middleware.use ::Rack::MethodOverride unless config.api_only
+ middleware.use ::ActionDispatch::RequestId
+ middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
+ middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || Rails::API::PublicExceptions.new(Rails.public_path)
+ middleware.use ::ActionDispatch::DebugExceptions
+ middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
+
+ unless config.cache_classes
+ app = self
+ middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
+ end
+
+ middleware.use ::ActionDispatch::Callbacks
+ middleware.use ::ActionDispatch::Cookies unless config.api_only
+
+ if !config.api_only && config.session_store
+ if config.force_ssl && !config.session_options.key?(:secure)
+ config.session_options[:secure] = true
+ end
+ middleware.use config.session_store, config.session_options
+ middleware.use ::ActionDispatch::Flash
+ end
+
+ middleware.use ::ActionDispatch::ParamsParser
+ middleware.use ::ActionDispatch::Head
+ middleware.use ::Rack::ConditionalGet
+ middleware.use ::Rack::ETag, "no-cache"
+
+ if !config.api_only && config.action_dispatch.best_standards_support
+ middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support
+ end
+ end
+ end
+ end
+end
--- /dev/null
+module Rails
+ class Application
+ class DefaultRailsFourMiddlewareStack
+ attr_reader :config, :paths, :app
+
+ def initialize(app, config, paths)
+ @app = app
+ @config = config
+ @paths = paths
+ end
+
+ def build_stack
+ ActionDispatch::MiddlewareStack.new.tap do |middleware|
+ if rack_cache = load_rack_cache
+ require "action_dispatch/http/rack_cache"
+ middleware.use ::Rack::Cache, rack_cache
+ end
+
+ if config.force_ssl
+ middleware.use ::ActionDispatch::SSL, config.ssl_options
+ end
+
+ if config.action_dispatch.x_sendfile_header.present?
+ middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
+ end
+
+ if config.serve_static_assets
+ middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
+ end
+
+ middleware.use ::Rack::Lock unless allow_concurrency?
+ middleware.use ::Rack::Runtime
+ middleware.use ::Rack::MethodOverride unless config.api_only
+ middleware.use ::ActionDispatch::RequestId
+
+ # Must come after Rack::MethodOverride to properly log overridden methods
+ middleware.use ::Rails::Rack::Logger, config.log_tags
+ middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
+ middleware.use ::ActionDispatch::DebugExceptions, app
+ middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
+
+ unless config.cache_classes
+ middleware.use ::ActionDispatch::Reloader, lambda { reload_dependencies? }
+ end
+
+ middleware.use ::ActionDispatch::Callbacks
+ middleware.use ::ActionDispatch::Cookies unless config.api_only
+
+ if !config.api_only && config.session_store
+ if config.force_ssl && !config.session_options.key?(:secure)
+ config.session_options[:secure] = true
+ end
+ middleware.use config.session_store, config.session_options
+ middleware.use ::ActionDispatch::Flash
+ end
+
+ middleware.use ::ActionDispatch::ParamsParser
+ middleware.use ::Rack::Head
+ middleware.use ::Rack::ConditionalGet
+ middleware.use ::Rack::ETag, "no-cache"
+ end
+ end
+
+ private
+
+ def reload_dependencies?
+ config.reload_classes_only_on_change != true || app.reloaders.map(&:updated?).any?
+ end
+
+ def allow_concurrency?
+ config.allow_concurrency.nil? ? config.cache_classes : config.allow_concurrency
+ end
+
+ def load_rack_cache
+ rack_cache = config.action_dispatch.rack_cache
+ return unless rack_cache
+
+ begin
+ require 'rack/cache'
+ rescue LoadError => error
+ error.message << ' Be sure to add rack-cache to your Gemfile'
+ raise
+ end
+
+ if rack_cache == true
+ {
+ metastore: "rails:/",
+ entitystore: "rails:/",
+ verbose: false
+ }
+ else
+ rack_cache
+ end
+ end
+
+ def show_exceptions_app
+ config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
+ end
+ end
+ end
+end
--- /dev/null
+require 'rails/generators'
+require 'rails/generators/rails/app/app_generator'
+
+Rails::Generators::AppGenerator.source_paths.unshift(
+ File.expand_path('../../../../templates/rails/app', __FILE__)
+)
+
+class Rails::AppBuilder
+ undef tmp
+ undef vendor
+end
--- /dev/null
+module Rails
+ module API
+ class PublicExceptions
+ attr_accessor :public_path
+
+ def initialize(public_path)
+ @public_path = public_path
+ end
+
+ def call(env)
+ exception = env["action_dispatch.exception"]
+ status = env["PATH_INFO"][1..-1]
+ request = ActionDispatch::Request.new(env)
+ content_type = request.formats.first
+ body = { :status => status, :error => exception.message }
+
+ render(status, content_type, body)
+ end
+
+ private
+
+ def render(status, content_type, body)
+ format = content_type && "to_#{content_type.to_sym}"
+ if format && body.respond_to?(format)
+ render_format(status, content_type, body.public_send(format))
+ else
+ render_html(status)
+ end
+ end
+
+ def render_format(status, content_type, body)
+ [status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
+ 'Content-Length' => body.bytesize.to_s}, [body]]
+ end
+
+ def render_html(status)
+ found = false
+ path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
+ path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
+
+ if found || File.exist?(path)
+ render_format(status, 'text/html', File.read(path))
+ else
+ [404, { "X-Cascade" => "pass" }, []]
+ end
+ end
+ end
+ end
+end
--- /dev/null
+source 'https://rubygems.org'
+
+<%= rails_gemfile_entry -%>
+
+gem 'rails-api'
+
+<%= database_gemfile_entry -%>
+
+<%= "gem 'jruby-openssl'\n" if defined?(JRUBY_VERSION) -%>
+<%= "gem 'json'\n" if RUBY_VERSION < "1.9.2" -%>
+
+# To use ActiveModel has_secure_password
+# gem 'bcrypt-ruby', '~> 3.0.0'
+
+# To use Jbuilder templates for JSON
+# gem 'jbuilder'
+
+# Use unicorn as the app server
+# gem 'unicorn'
+
+# Deploy with Capistrano
+# gem 'capistrano', :group => :development
+
+# To use debugger
+# gem 'ruby-debug19', :require => 'ruby-debug'
--- /dev/null
+class ApplicationController < ActionController::API
+end
--- /dev/null
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+# You can use `rake secret` to generate a secure secret key.
+
+# Make sure your secret_key_base is kept private
+# if you're sharing your code publicly.
+
+# Although this is not needed for an api-only application, rails4
+# requires secret_key_base or secret_token to be defined, otherwise an
+# error is raised.
+# Using secret_token for rails3 compatibility. Change to secret_key_base
+# to avoid deprecation warning.
+# Can be safely removed in a rails3 api-only application.
+<%= app_const %>.config.secret_token = '<%= app_secret %>'
--- /dev/null
+# Be sure to restart your server when you modify this file.
+#
+# This file contains settings for ActionController::ParamsWrapper
+
+# Enable parameter wrapping for JSON.
+# ActiveSupport.on_load(:action_controller) do
+# wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
+# end
+
+<%- unless options.skip_active_record? -%>
+# To enable root element in JSON for ActiveRecord objects.
+# ActiveSupport.on_load(:active_record) do
+# self.include_root_in_json = true
+# end
+<%- end -%>
--- /dev/null
+<% module_namespacing do -%>
+class <%= controller_class_name %>Controller < ApplicationController
+ # GET <%= route_url %>
+ # GET <%= route_url %>.json
+ def index
+ @<%= plural_table_name %> = <%= orm_class.all(class_name) %>
+
+ render json: <%= "@#{plural_table_name}" %>
+ end
+
+ # GET <%= route_url %>/1
+ # GET <%= route_url %>/1.json
+ def show
+ @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+
+ render json: <%= "@#{singular_table_name}" %>
+ end
+
+ # POST <%= route_url %>
+ # POST <%= route_url %>.json
+ def create
+ @<%= singular_table_name %> = <%= orm_class.build(class_name, "params[:#{singular_table_name}]") %>
+
+ if @<%= orm_instance.save %>
+ render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %>
+ else
+ render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
+ end
+ end
+
+ # PATCH/PUT <%= route_url %>/1
+ # PATCH/PUT <%= route_url %>/1.json
+ def update
+ @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+
+ if @<%= Rails::API.rails4? ? orm_instance.update("params[:#{singular_table_name}]") : orm_instance.update_attributes("params[:#{singular_table_name}]") %>
+ head :no_content
+ else
+ render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity
+ end
+ end
+
+ # DELETE <%= route_url %>/1
+ # DELETE <%= route_url %>/1.json
+ def destroy
+ @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+ @<%= orm_instance.destroy %>
+
+ head :no_content
+ end
+end
+<% end -%>
--- /dev/null
+require 'test_helper'
+
+<% module_namespacing do -%>
+class <%= controller_class_name %>ControllerTest < ActionController::TestCase
+ setup do
+ @<%= singular_table_name %> = <%= table_name %>(:one)
+ end
+
+ test "should get index" do
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:<%= table_name %>)
+ end
+
+ test "should create <%= singular_table_name %>" do
+ assert_difference('<%= class_name %>.count') do
+ post :create, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
+ end
+
+ assert_response 201
+ end
+
+ test "should show <%= singular_table_name %>" do
+ get :show, id: <%= "@#{singular_table_name}" %>
+ assert_response :success
+ end
+
+ test "should update <%= singular_table_name %>" do
+ put :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
+ assert_response 204
+ end
+
+ test "should destroy <%= singular_table_name %>" do
+ assert_difference('<%= class_name %>.count', -1) do
+ delete :destroy, id: <%= "@#{singular_table_name}" %>
+ end
+
+ assert_response 204
+ end
+end
+<% end -%>
--- /dev/null
+module Rails
+ module API
+ VERSION = '0.2.0'
+ end
+end
--- /dev/null
+--- !ruby/object:Gem::Specification
+name: rails-api
+version: !ruby/object:Gem::Version
+ version: 0.2.0
+platform: ruby
+authors:
+- Santiago Pastorino and Carlos Antonio da Silva
+autorequire:
+bindir: bin
+cert_chain: []
+date: 2014-01-13 00:00:00.000000000 Z
+dependencies:
+- !ruby/object:Gem::Dependency
+ name: actionpack
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+ type: :runtime
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+- !ruby/object:Gem::Dependency
+ name: railties
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+ type: :runtime
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+- !ruby/object:Gem::Dependency
+ name: rails
+ requirement: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+ type: :development
+ prerelease: false
+ version_requirements: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 3.2.11
+description: |-
+ Rails::API is a subset of a normal Rails application,
+ created for applications that don't require all
+ functionality that a complete Rails application provides
+email:
+- "<santiago@wyeworks.com>"
+- "<carlosantoniodasilva@gmail.com>"
+executables:
+- rails-api
+extensions: []
+extra_rdoc_files: []
+files:
+- LICENSE
+- README.md
+- bin/rails-api
+- lib/generators/rails/api_resource_route/api_resource_route_generator.rb
+- lib/rails-api.rb
+- lib/rails-api/action_controller/api.rb
+- lib/rails-api/application.rb
+- lib/rails-api/application/default_rails_four_middleware_stack.rb
+- lib/rails-api/generators/rails/app/app_generator.rb
+- lib/rails-api/public_exceptions.rb
+- lib/rails-api/templates/rails/app/Gemfile
+- lib/rails-api/templates/rails/app/app/controllers/application_controller.rb.tt
+- lib/rails-api/templates/rails/app/config/initializers/secret_token.rb.tt
+- lib/rails-api/templates/rails/app/config/initializers/wrap_parameters.rb.tt
+- lib/rails-api/templates/rails/scaffold_controller/controller.rb
+- lib/rails-api/templates/test_unit/scaffold/functional_test.rb
+- lib/rails-api/version.rb
+- test/api_application/api_application_test.rb
+- test/api_controller/action_methods_test.rb
+- test/api_controller/conditional_get_test.rb
+- test/api_controller/data_streaming_test.rb
+- test/api_controller/force_ssl_test.rb
+- test/api_controller/redirect_to_test.rb
+- test/api_controller/renderers_test.rb
+- test/api_controller/url_for_test.rb
+- test/generators/app_generator_test.rb
+- test/generators/fixtures/routes.rb
+- test/generators/generators_test_helper.rb
+- test/generators/resource_generator_test.rb
+- test/generators/scaffold_generator_test.rb
+- test/test_helper.rb
+homepage: https://github.com/rails-api/rails-api
+licenses:
+- MIT
+metadata: {}
+post_install_message:
+rdoc_options: []
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: '0'
+required_rubygems_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: 1.3.6
+requirements: []
+rubyforge_project:
+rubygems_version: 2.2.0
+signing_key:
+specification_version: 4
+summary: Rails for API only Applications
+test_files:
+- test/api_application/api_application_test.rb
+- test/api_controller/action_methods_test.rb
+- test/api_controller/conditional_get_test.rb
+- test/api_controller/data_streaming_test.rb
+- test/api_controller/force_ssl_test.rb
+- test/api_controller/redirect_to_test.rb
+- test/api_controller/renderers_test.rb
+- test/api_controller/url_for_test.rb
+- test/generators/app_generator_test.rb
+- test/generators/fixtures/routes.rb
+- test/generators/generators_test_helper.rb
+- test/generators/resource_generator_test.rb
+- test/generators/scaffold_generator_test.rb
+- test/test_helper.rb
--- /dev/null
+require 'test_helper'
+require 'action_controller/railtie'
+require 'rack/test'
+
+class OmgController < ActionController::API
+ def index
+ render :text => "OMG"
+ end
+
+ def unauthorized
+ render :text => "get out", :status => :unauthorized
+ end
+end
+
+class ApiApplicationTest < ActiveSupport::TestCase
+ include ::Rack::Test::Methods
+
+ app.initialize!
+
+ def test_boot_api_app
+ get "/omg"
+ assert_equal "OMG", last_response.body
+ end
+
+ def test_proper_status_set
+ get "/omg/unauthorized"
+ assert_equal 401, last_response.status
+ end
+
+ def test_api_middleware_stack
+ expected_middleware_stack =
+ rails4? ? expected_middleware_stack_rails4 : expected_middleware_stack_rails3
+
+ assert_equal expected_middleware_stack, app.middleware.map(&:klass).map(&:name)
+ end
+
+ private
+
+ def expected_middleware_stack_rails3
+ [
+ "ActionDispatch::Static",
+ "Rack::Lock",
+ "ActiveSupport::Cache::Strategy::LocalCache",
+ "Rack::Runtime",
+ "ActionDispatch::RequestId",
+ "Rails::Rack::Logger",
+ "ActionDispatch::ShowExceptions",
+ "ActionDispatch::DebugExceptions",
+ "ActionDispatch::RemoteIp",
+ "ActionDispatch::Reloader",
+ "ActionDispatch::Callbacks",
+ "ActionDispatch::ParamsParser",
+ "ActionDispatch::Head",
+ "Rack::ConditionalGet",
+ "Rack::ETag"
+ ]
+ end
+
+ def expected_middleware_stack_rails4
+ [
+ "ActionDispatch::Static",
+ "Rack::Lock",
+ "ActiveSupport::Cache::Strategy::LocalCache",
+ "Rack::Runtime",
+ "ActionDispatch::RequestId",
+ "Rails::Rack::Logger",
+ "ActionDispatch::ShowExceptions",
+ "ActionDispatch::DebugExceptions",
+ "ActionDispatch::RemoteIp",
+ "ActionDispatch::Reloader",
+ "ActionDispatch::Callbacks",
+ "ActionDispatch::ParamsParser",
+ "Rack::Head",
+ "Rack::ConditionalGet",
+ "Rack::ETag",
+ ]
+ end
+end
--- /dev/null
+require 'test_helper'
+
+class ActionMethodsApiController < ActionController::API
+ def one; end
+ def two; end
+ hide_action :two
+end
+
+class ActionMethodsApiTest < ActionController::TestCase
+ tests ActionMethodsApiController
+
+ def test_action_methods
+ assert_equal Set.new(%w(one)),
+ @controller.class.action_methods,
+ "#{@controller.controller_path} should not be empty!"
+ end
+end
--- /dev/null
+require 'test_helper'
+require 'active_support/core_ext/integer/time'
+require 'active_support/core_ext/numeric/time'
+
+class ConditionalGetApiController < ActionController::API
+ before_filter :handle_last_modified_and_etags, :only => :two
+
+ def one
+ if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123])
+ render :text => "Hi!"
+ end
+ end
+
+ def two
+ render :text => "Hi!"
+ end
+
+ private
+
+ def handle_last_modified_and_etags
+ fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
+ end
+end
+
+class ConditionalGetApiTest < ActionController::TestCase
+ tests ConditionalGetApiController
+
+ def setup
+ @last_modified = Time.now.utc.beginning_of_day.httpdate
+ end
+
+ def test_request_with_bang_gets_last_modified
+ get :two
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ assert_response :success
+ end
+
+ def test_request_with_bang_obeys_last_modified
+ @request.if_modified_since = @last_modified
+ get :two
+ assert_response :not_modified
+ end
+
+ def test_last_modified_works_with_less_than_too
+ @request.if_modified_since = 5.years.ago.httpdate
+ get :two
+ assert_response :success
+ end
+
+ def test_request_not_modified
+ @request.if_modified_since = @last_modified
+ get :one
+ assert_equal 304, @response.status.to_i
+ assert @response.body.blank?
+ assert_equal @last_modified, @response.headers['Last-Modified']
+ end
+end
--- /dev/null
+require 'test_helper'
+
+module TestApiFileUtils
+ def file_name() File.basename(__FILE__) end
+ def file_path() File.expand_path(__FILE__) end
+ def file_data() @data ||= File.open(file_path, 'rb') { |f| f.read } end
+end
+
+class DataStreamingApiController < ActionController::API
+ include TestApiFileUtils
+
+ def one; end
+ def two
+ send_data(file_data, {})
+ end
+end
+
+class DataStreamingApiTest < ActionController::TestCase
+ include TestApiFileUtils
+ tests DataStreamingApiController
+
+ def test_data
+ response = process('two')
+ assert_kind_of String, response.body
+ assert_equal file_data, response.body
+ end
+end
--- /dev/null
+require 'test_helper'
+
+class ForceSSLApiController < ActionController::API
+ force_ssl
+
+ def one; end
+ def two
+ head :ok
+ end
+end
+
+class ForceSSLApiTest < ActionController::TestCase
+ tests ForceSSLApiController
+
+ def test_redirects_to_https
+ get :two
+ assert_response 301
+ assert_equal "https://test.host/force_ssl_api/two", redirect_to_url
+ end
+end
--- /dev/null
+require 'test_helper'
+
+class RedirectToApiController < ActionController::API
+ def one
+ redirect_to :action => "two"
+ end
+
+ def two; end
+end
+
+class RedirectToApiTest < ActionController::TestCase
+ tests RedirectToApiController
+
+ def test_redirect_to
+ get :one
+ assert_response :redirect
+ assert_equal "http://test.host/redirect_to_api/two", redirect_to_url
+ end
+end
--- /dev/null
+require 'test_helper'
+require 'active_support/core_ext/hash/conversions'
+
+class Model
+ def to_json(options = {})
+ { :a => 'b' }.to_json(options)
+ end
+
+ def to_xml(options = {})
+ { :a => 'b' }.to_xml(options)
+ end
+end
+
+class RenderersApiController < ActionController::API
+ use ActionDispatch::ShowExceptions, Rails::API::PublicExceptions.new(Rails.public_path)
+
+ def one
+ render :json => Model.new
+ end
+
+ def two
+ render :xml => Model.new
+ end
+
+ def boom
+ raise "boom"
+ end
+end
+
+class RenderersApiTest < ActionController::TestCase
+ tests RenderersApiController
+
+ def test_render_json
+ get :one
+ assert_response :success
+ assert_equal({ :a => 'b' }.to_json, @response.body)
+ end
+
+ def test_render_xml
+ get :two
+ assert_response :success
+ assert_equal({ :a => 'b' }.to_xml, @response.body)
+ end
+end
+
+class RenderExceptionsTest < ActionDispatch::IntegrationTest
+ def setup
+ @app = RenderersApiController.action(:boom)
+ end
+
+ def test_render_json_exception
+ get "/fake", {}, 'HTTP_ACCEPT' => 'application/json'
+ assert_response :internal_server_error
+ assert_equal 'application/json', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom' }.to_json, response.body)
+ end
+
+ def test_render_xml_exception
+ get "/fake", {}, 'HTTP_ACCEPT' => 'application/xml'
+ assert_response :internal_server_error
+ assert_equal 'application/xml', response.content_type.to_s
+ assert_equal({ :status => '500', :error => 'boom' }.to_xml, response.body)
+ end
+
+ def test_render_fallback_exception
+ get "/fake", {}, 'HTTP_ACCEPT' => 'text/csv'
+ assert_response :internal_server_error
+ assert_equal 'text/html', response.content_type.to_s
+ end
+end
--- /dev/null
+require 'test_helper'
+
+class UrlForApiController < ActionController::API
+ def one; end
+ def two; end
+end
+
+class UrlForApiTest < ActionController::TestCase
+ tests UrlForApiController
+
+ def setup
+ super
+ @request.host = 'www.example.com'
+ end
+
+ def test_url_for
+ get :one
+ assert_equal "http://www.example.com/url_for_api/one", @controller.url_for
+ end
+end
--- /dev/null
+require 'generators/generators_test_helper'
+require 'rails-api/generators/rails/app/app_generator'
+
+class AppGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ arguments [destination_root]
+
+ def test_skeleton_is_created
+ run_generator
+
+ default_files.each { |path| assert_file path }
+ skipped_files.each { |path| assert_no_file path }
+ end
+
+ def test_api_modified_files
+ run_generator
+
+ assert_file "Gemfile" do |content|
+ assert_match(/gem 'rails-api'/, content)
+ assert_no_match(/gem 'coffee-rails'/, content)
+ assert_no_match(/gem 'jquery-rails'/, content)
+ assert_no_match(/gem 'sass-rails'/, content)
+ end
+ assert_file "app/controllers/application_controller.rb", /ActionController::API/
+ end
+
+ private
+
+ def default_files
+ files = %W(
+ .gitignore
+ Gemfile
+ Rakefile
+ config.ru
+ app/controllers
+ app/mailers
+ app/models
+ config/environments
+ config/initializers
+ config/locales
+ db
+ lib
+ lib/tasks
+ lib/assets
+ log
+ test/fixtures
+ test/#{generated_test_functional_dir}
+ test/integration
+ test/#{generated_test_unit_dir}
+ )
+ files.concat rails4? ? default_files_rails4 : default_files_rails3
+ files
+ end
+
+ def default_files_rails3
+ %w(script/rails)
+ end
+
+ def default_files_rails4
+ %w(bin/bundle bin/rails bin/rake)
+ end
+
+ def skipped_files
+ %w(vendor/assets
+ tmp/cache/assets)
+ end
+end
--- /dev/null
+Rails.application.routes.draw do
+end
--- /dev/null
+require 'test_helper'
+require 'rails/generators'
+
+module GeneratorsTestHelper
+ def self.included(base)
+ base.class_eval do
+ destination File.expand_path("../../tmp", __FILE__)
+ setup :prepare_destination
+ teardown :remove_destination
+
+ begin
+ base.tests Rails::Generators.const_get(base.name.sub(/Test$/, ''))
+ rescue
+ end
+ end
+ end
+
+ private
+
+ def copy_routes
+ routes = File.expand_path("../fixtures/routes.rb", __FILE__)
+ destination = File.join(destination_root, "config")
+ FileUtils.mkdir_p(destination)
+ FileUtils.cp routes, destination
+ end
+
+ def generated_test_unit_dir
+ rails4? ? 'models' : 'unit'
+ end
+
+ def generated_test_functional_dir
+ rails4? ? 'controllers' : 'functional'
+ end
+
+ def remove_destination
+ rm_rf destination_root
+ end
+end
--- /dev/null
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/resource/resource_generator'
+
+class ResourceGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ arguments %w(account)
+ setup :copy_routes
+
+ def test_resource_routes_are_added
+ run_generator
+
+ assert_file "config/routes.rb" do |route|
+ assert_match(/resources :accounts, except: \[:new, :edit\]$/, route)
+ assert_no_match(/resources :accounts$/, route)
+ end
+ end
+end
--- /dev/null
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/scaffold/scaffold_generator'
+
+class ScaffoldGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+
+ arguments %w(product_line title:string product:belongs_to user:references)
+ setup :copy_routes
+
+ def test_scaffold_on_invoke
+ run_generator
+
+ # Model
+ assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
+ assert_file "test/#{generated_test_unit_dir}/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
+ assert_file "test/fixtures/product_lines.yml"
+
+ if rails4?
+ assert_migration "db/migrate/create_product_lines.rb",
+ /belongs_to :product, index: true/,
+ /references :user, index: true/
+ else
+ assert_migration "db/migrate/create_product_lines.rb",
+ /belongs_to :product/,
+ /add_index :product_lines, :product_id/,
+ /references :user/,
+ /add_index :product_lines, :user_id/
+ end
+
+ # Route
+ assert_file "config/routes.rb" do |content|
+ assert_match(/resources :product_lines, except: \[:new, :edit\]$/, content)
+ assert_no_match(/resource :product_lines$/, content)
+ end
+
+ # Controller
+ assert_file "app/controllers/product_lines_controller.rb" do |content|
+ assert_match(/class ProductLinesController < ApplicationController/, content)
+ assert_no_match(/respond_to/, content)
+
+ assert_instance_method :index, content do |m|
+ assert_match(/@product_lines = ProductLine\.all/, m)
+ end
+
+ assert_instance_method :show, content do |m|
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ end
+
+ assert_instance_method :create, content do |m|
+ assert_match(/@product_line = ProductLine\.new\(params\[:product_line\]\)/, m)
+ assert_match(/@product_line\.save/, m)
+ assert_match(/@product_line\.errors/, m)
+ end
+
+ assert_instance_method :update, content do |m|
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ if rails4?
+ assert_match(/@product_line\.update\(params\[:product_line\]\)/, m)
+ else
+ assert_match(/@product_line\.update_attributes\(params\[:product_line\]\)/, m)
+ end
+ assert_match(/@product_line\.errors/, m)
+ end
+
+ assert_instance_method :destroy, content do |m|
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ assert_match(/@product_line\.destroy/, m)
+ end
+ end
+
+ assert_file "test/#{generated_test_functional_dir}/product_lines_controller_test.rb" do |test|
+ assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
+ if rails4?
+ assert_match(/post :create, product_line: \{ product_id: @product_line.product_id, title: @product_line.title, user_id: @product_line.user_id \}/, test)
+ assert_match(/put :update, id: @product_line, product_line: \{ product_id: @product_line.product_id, title: @product_line.title, user_id: @product_line.user_id \}/, test)
+ else
+ assert_match(/post :create, product_line: \{ title: @product_line.title \}/, test)
+ assert_match(/put :update, id: @product_line, product_line: \{ title: @product_line.title \}/, test)
+ end
+ assert_no_match(/assert_redirected_to/, test)
+ end
+
+ # Views
+ %w(index edit new show _form).each do |view|
+ assert_no_file "app/views/product_lines/#{view}.html.erb"
+ end
+ assert_no_file "app/views/layouts/product_lines.html.erb"
+
+ # Helpers
+ assert_no_file "app/helpers/product_lines_helper.rb"
+ assert_no_file "test/#{generated_test_unit_dir}/helpers/product_lines_helper_test.rb"
+
+ # Assets
+ assert_no_file "app/assets/stylesheets/scaffold.css"
+ assert_no_file "app/assets/stylesheets/product_lines.css"
+ assert_no_file "app/assets/javascripts/product_lines.js"
+ end
+end
--- /dev/null
+# Configure Rails Environment
+ENV["RAILS_ENV"] = "test"
+
+require 'bundler/setup'
+require 'rails'
+require 'rails/test_help'
+require 'rails-api'
+
+def rails4?
+ Rails::API.rails4?
+end
+
+class ActiveSupport::TestCase
+ def self.app
+ @@app ||= Class.new(Rails::Application) do
+ config.active_support.deprecation = :stderr
+ config.generators do |c|
+ c.orm :active_record, :migration => true,
+ :timestamps => true
+
+ c.test_framework :test_unit, :fixture => true,
+ :fixture_replacement => nil
+
+ c.integration_tool :test_unit
+ c.performance_tool :test_unit
+ end
+
+ if rails4?
+ config.eager_load = false
+ config.secret_key_base = 'abc123'
+ end
+
+ def self.name
+ 'TestApp'
+ end
+ end
+ end
+
+ def app
+ self.class.app
+ end
+
+ app.routes.append do
+ get ':controller(/:action)'
+ end
+ app.routes.finalize!
+
+ app.load_generators
+end
+
+module ActionController
+ class API
+ include ActiveSupport::TestCase.app.routes.url_helpers
+ end
+end
+
+Rails.logger = Logger.new("/dev/null")