Skip to content

Complete, fast and testable actions for Rack and Hanami

License

Notifications You must be signed in to change notification settings

TrumpClone/controller

Repository files navigation

Hanami::Controller

Complete, fast and testable actions for Rack and Hanami

Status

Gem VersionBuild StatusCoverageCode ClimateDependenciesInline docs

Contact

Rubies

Hanami::Controller supports Ruby (MRI) 2.3+ and JRuby 9.1.5.0+

Installation

Add this line to your application's Gemfile:

gem'hanami-controller'

And then execute:

$ bundle

Or install it yourself as:

$ gem install hanami-controller

Usage

Hanami::Controller is a micro library for web frameworks. It works beautifully with Hanami::Router, but it can be employed everywhere. It's designed to be fast and testable.

Actions

The core of this framework are the actions. They are the endpoints that respond to incoming HTTP requests.

classShowincludeHanami::Actiondefcall(params)@article=ArticleRepository.new.find(params[:id])endend

The usage of Hanami::Action follows the Hanami philosophy: include a module and implement a minimal interface. In this case, the interface is one method: #call(params).

Hanami is designed to not interfere with inheritance. This is important, because you can implement your own initialization strategy.

An action is an object. That's important because you have the full control on it. In other words, you have the freedom to instantiate, inject dependencies and test it, both at the unit and integration level.

In the example below, the default repository is ArticleRepository. During a unit test we can inject a stubbed version, and invoke #call with the params. We're avoiding HTTP calls, we're also going to avoid hitting the database (it depends on the stubbed repository), we're just dealing with message passing. Imagine how fast the unit test could be.

classShowincludeHanami::Actiondefinitialize(repository=ArticleRepository.new)@repository=repositoryenddefcall(params)@article=@repository.find(params[:id])endendaction=Show.new(MemoryArticleRepository.new)action.call({id: 23})

Params

The request params are passed as an argument to the #call method. If routed with Hanami::Router, it extracts the relevant bits from the Rack env (eg the requested :id). Otherwise everything is passed as is: the full Rack env in production, and the given Hash for unit tests.

With Hanami::Router:

classShowincludeHanami::Actiondefcall(params)# ...putsparams# =>{id: 23 } extracted from Rack envendend

Standalone:

classShowincludeHanami::Actiondefcall(params)# ...putsparams# =>{:"rack.version"=>[1, 2], :"rack.input"=>#<StringIO:0x007fa563463948>, ... }endend

Unit Testing:

classShowincludeHanami::Actiondefcall(params)# ...putsparams# =>{id: 23, key: 'value' } passed as it is from testingendendaction=Show.newresponse=action.call({id: 23,key: 'value'})

Whitelisting

Params represent an untrusted input. For security reasons it's recommended to whitelist them.

require'hanami/validations'require'hanami/controller'classSignupincludeHanami::Actionparamsdorequired(:first_name).filled(:str?)required(:last_name).filled(:str?)required(:email).filled(:str?)required(:address).schemadorequired(:line_one).filled(:str?)required(:state).filled(:str?)required(:country).filled(:str?)endenddefcall(params)# Describe inheritance hierarchyputsparams.class# => Signup::Paramsputsparams.class.superclass# => Hanami::Action::Params# Whitelist :first_name, but not :adminputsparams[:first_name]# => "Luca"putsparams[:admin]# => nil# Whitelist nested params [:address][:line_one], not [:address][:line_two]putsparams[:address][:line_one]# => '69 Tender St'putsparams[:address][:line_two]# => nilendend

Validations & Coercions

Because params are a well defined set of data required to fulfill a feature in your application, you can validate them. So you can avoid hitting lower MVC layers when params are invalid.

If you specify the :type option, the param will be coerced.

require'hanami/validations'require'hanami/controller'classSignupMEGABYTE=1024 ** 2includeHanami::Actionparamsdorequired(:first_name).filled(:str?)required(:last_name).filled(:str?)required(:email).confirmation.filled?(:str?,format?: /@/)required(:password).confirmation.filled(:str?)required(:terms_of_service).filled(:bool?)required(:age).filled(:int?,included_in?: 18..99)optional(:avatar).filled(size?: 1..(MEGABYTE * 3))enddefcall(params)halt400unlessparams.valid?# ...endendaction=Signup.newaction.call(valid_params)# => [200,{}, ...]action.errors.empty?# => trueaction.call(invalid_params)# => [400,{}, ...]action.errors.empty?# => falseaction.errors.fetch(:email)# => ['is missing', 'is in invalid format']

Response

The output of #call is a serialized Rack::Response (see #finish):

classShowincludeHanami::Actiondefcall(params)# ...endendaction=Show.newaction.call({})# => [200,{}, [""]]

It has private accessors to explicitly set status, headers, and body:

classShowincludeHanami::Actiondefcall(params)self.status=201self.body='Hi!'self.headers.merge!({'X-Custom'=>'OK'})endendaction=Show.newaction.call({})# => [201,{"X-Custom" => "OK" }, ["Hi!"]]

Exposures

We know that actions are objects and Hanami::Action respects one of the pillars of OOP: encapsulation. Other frameworks extract instance variables (@ivar) and make them available to the view context.

Hanami::Action's solution is the simple and powerful DSL: expose. It's a thin layer on top of attr_reader.

Using expose creates a getter for the given attribute, and adds it to the exposures. Exposures (#exposures) are a set of attributes exposed to the view. That is to say the variables necessary for rendering a view.

By default, all Hanami::Action objects expose #params and #errors.

classShowincludeHanami::Actionexpose:articledefcall(params)@article=ArticleRepository.new.find(params[:id])endendaction=Show.newaction.call({id: 23})assert_equal23,action.article.idputsaction.exposures# =>{article: <Article:0x007f965c1d0318 @id=23>}

Callbacks

It offers a powerful, inheritable callback chain which is executed before and/or after your #call method invocation:

classShowincludeHanami::Actionbefore:authenticate,:set_articledefcall(params)endprivatedefauthenticate# ...end# `params` in the method signature is optionaldefset_article(params)@article=ArticleRepository.new.find(params[:id])endend

Callbacks can also be expressed as anonymous lambdas:

classShowincludeHanami::Actionbefore{ ... }# do some authentication stuffbefore{ |params| @article=ArticleRepository.new.find(params[:id])}defcall(params)endend

Exceptions management

When an exception is raised, it automatically sets the HTTP status to 500:

classShowincludeHanami::Actiondefcall(params)raiseendendaction=Show.newaction.call({})# => [500,{}, ["Internal Server Error"]]

You can map a specific raised exception to a different HTTP status.

classShowincludeHanami::Actionhandle_exceptionRecordNotFound=>404defcall(params)@article=ArticleRepository.new.find(params[:id])endendaction=Show.newaction.call({id: 'unknown'})# => [404,{}, ["Not Found"]]

You can also define custom handlers for exceptions.

classCreateincludeHanami::Actionhandle_exceptionArgumentError=>:my_custom_handlerdefcall(params)raiseArgumentError.new("Invalid arguments")endprivatedefmy_custom_handler(exception)status400,exception.messageendendaction=Create.newaction.call({})# => [400,{}, ["Invalid arguments"]]

Exception policies can be defined globally, before the controllers/actions are loaded.

Hanami::Controller.configuredohandle_exceptionRecordNotFound=>404endclassShowincludeHanami::Actiondefcall(params)@article=ArticleRepository.new.find(params[:id])endendaction=Show.newaction.call({id: 'unknown'})# => [404,{}, ["Not Found"]]

This feature can be turned off globally, in a controller or in a single action.

Hanami::Controller.configuredohandle_exceptionsfalseend# ormoduleArticlesclassShowincludeHanami::Actionconfiguredohandle_exceptionsfalseenddefcall(params)@article=ArticleRepository.new.find(params[:id])endendendaction=Articles::Show.newaction.call({id: 'unknown'})# => raises RecordNotFound

Inherited Exceptions

classMyCustomException < StandardErrorendmoduleArticlesclassIndexincludeHanami::Actionhandle_exceptionMyCustomException=>:handle_my_exceptiondefcall(params)raiseMyCustomExceptionendprivatedefhandle_my_exception# ...endendclassShowincludeHanami::Actionhandle_exceptionStandardError=>:handle_standard_errordefcall(params)raiseMyCustomExceptionendprivatedefhandle_standard_error# ...endendendArticles::Index.new.call({})# => `handle_my_exception` will be invokedArticles::Show.new.call({})# => `handle_standard_error` will be invoked,# because `MyCustomException` inherits from `StandardError`

Throwable HTTP statuses

When #halt is used with a valid HTTP code, it stops the execution and sets the proper status and body for the response:

classShowincludeHanami::Actionbefore:authenticate!defcall(params)# ...endprivatedefauthenticate!halt401unlessauthenticated?endendaction=Show.newaction.call({})# => [401,{}, ["Unauthorized"]]

Alternatively, you can specify a custom message.

classShowincludeHanami::Actiondefcall(params)DroidRepository.new.find(params[:id])ornot_foundendprivatedefnot_foundhalt404,"This is not the droid you're looking for"endendaction=Show.newaction.call({})# => [404,{}, ["This is not the droid you're looking for"]]

Cookies

Hanami::Controller offers convenient access to cookies.

They are read as a Hash from Rack env:

require'hanami/controller'require'hanami/action/cookies'classReadCookiesFromRackEnvincludeHanami::ActionincludeHanami::Action::Cookiesdefcall(params)# ...cookies[:foo]# => 'bar'endendaction=ReadCookiesFromRackEnv.newaction.call({'HTTP_COOKIE'=>'foo=bar'})

They are set like a Hash:

require'hanami/controller'require'hanami/action/cookies'classSetCookiesincludeHanami::ActionincludeHanami::Action::Cookiesdefcall(params)# ...cookies[:foo]='bar'endendaction=SetCookies.newaction.call({})# => [200,{'Set-Cookie' => 'foo=bar'}, '...']

They are removed by setting their value to nil:

require'hanami/controller'require'hanami/action/cookies'classRemoveCookiesincludeHanami::ActionincludeHanami::Action::Cookiesdefcall(params)# ...cookies[:foo]=nilendendaction=RemoveCookies.newaction.call({})# => [200,{'Set-Cookie' => "foo=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"}, '...']

Default values can be set in configuration, but overriden case by case.

require'hanami/controller'require'hanami/action/cookies'Hanami::Controller.configuredocookiesmax_age: 300# 5 minutesendclassSetCookiesincludeHanami::ActionincludeHanami::Action::Cookiesdefcall(params)# ...cookies[:foo]={value: 'bar',max_age: 100}endendaction=SetCookies.newaction.call({})# => [200,{'Set-Cookie' => "foo=bar; max-age=100;"}, '...']

Sessions

It has builtin support for Rack sessions:

require'hanami/controller'require'hanami/action/session'classReadSessionFromRackEnvincludeHanami::ActionincludeHanami::Action::Sessiondefcall(params)# ...session[:age]# => '31'endendaction=ReadSessionFromRackEnv.newaction.call({'rack.session'=>{'age'=>'31'}})

Values can be set like a Hash:

require'hanami/controller'require'hanami/action/session'classSetSessionincludeHanami::ActionincludeHanami::Action::Sessiondefcall(params)# ...session[:age]=31endendaction=SetSession.newaction.call({})# => [200,{"Set-Cookie"=>"rack.session=..."}, "..."]

Values can be removed like a Hash:

require'hanami/controller'require'hanami/action/session'classRemoveSessionincludeHanami::ActionincludeHanami::Action::Sessiondefcall(params)# ...session[:age]=nilendendaction=RemoveSession.newaction.call({})# => [200,{"Set-Cookie"=>"rack.session=..."}, "..."] it removes that value from the session

While Hanami::Controller supports sessions natively, it's session store agnostic. You have to specify the session store in your Rack middleware configuration (eg config.ru).

useRack::Session::Cookie,secret: SecureRandom.hex(64)runShow.new

Http Cache

Hanami::Controller sets your headers correctly according to RFC 2616 / 14.9 for more on standard cache control directives: http://tools.ietf.org/html/rfc2616#section-14.9.1

You can easily set the Cache-Control header for your actions:

require'hanami/controller'require'hanami/action/cache'classHttpCacheControllerincludeHanami::ActionincludeHanami::Action::Cachecache_control:public,max_age: 600# => Cache-Control: public, max-age=600defcall(params)# ...endend

Expires header can be specified using expires method:

require'hanami/controller'require'hanami/action/cache'classHttpCacheControllerincludeHanami::ActionincludeHanami::Action::Cacheexpires60,:public,max_age: 600# => Expires: Sun, 03 Aug 2014 17:47:02 GMT, Cache-Control: public, max-age=600defcall(params)# ...endend

Conditional Get

According to HTTP specification, conditional GETs provide a way for web servers to inform clients that the response to a GET request hasn't change since the last request returning a Not Modified header (304).

Passing the HTTP_IF_NONE_MATCH (content identifier) or HTTP_IF_MODIFIED_SINCE (timestamp) headers allows the web server define if the client has a fresh version of a given resource.

You can easily take advantage of Conditional Get using #fresh method:

require'hanami/controller'require'hanami/action/cache'classConditionalGetControllerincludeHanami::ActionincludeHanami::Action::Cachedefcall(params)# ...freshetag: @resource.cache_key# => halt 304 with header IfNoneMatch = @resource.cache_keyendend

If @resource.cache_key is equal to IfNoneMatch header, then hanami will halt 304.

The same behavior is accomplished using last_modified:

require'hanami/controller'require'hanami/action/cache'classConditionalGetControllerincludeHanami::ActionincludeHanami::Action::Cachedefcall(params)# ...freshlast_modified: @resource.update_at# => halt 304 with header IfModifiedSince = @resource.update_at.httpdateendend

If @resource.update_at is equal to IfModifiedSince header, then hanami will halt 304.

Redirect

If you need to redirect the client to another resource, use #redirect_to:

classCreateincludeHanami::Actiondefcall(params)# ...redirect_to'http://example.com/articles/23'endendaction=Create.newaction.call({article: {title: 'Hello'}})# => [302,{'Location' => '/articles/23'}, '']

You can also redirect with a custom status code:

classCreateincludeHanami::Actiondefcall(params)# ...redirect_to'http://example.com/articles/23',status: 301endendaction=Create.newaction.call({article: {title: 'Hello'}})# => [301,{'Location' => '/articles/23'}, '']

MIME Types

Hanami::Action automatically sets the Content-Type header, according to the request.

classShowincludeHanami::Actiondefcall(params)endendaction=Show.newaction.call({'HTTP_ACCEPT'=>'*/*'})# Content-Type "application/octet-stream"action.format# :allaction.call({'HTTP_ACCEPT'=>'text/html'})# Content-Type "text/html"action.format# :html

However, you can force this value:

classShowincludeHanami::Actiondefcall(params)# ...self.format=:jsonendendaction=Show.newaction.call({'HTTP_ACCEPT'=>'*/*'})# Content-Type "application/json"action.format# :jsonaction.call({'HTTP_ACCEPT'=>'text/html'})# Content-Type "application/json"action.format# :json

You can restrict the accepted MIME types:

classShowincludeHanami::Actionaccept:html,:jsondefcall(params)# ...endend# When called with "\*/\*" => 200# When called with "text/html" => 200# When called with "application/json" => 200# When called with "application/xml" => 406

You can check if the requested MIME type is accepted by the client.

classShowincludeHanami::Actiondefcall(params)# ...# @_env['HTTP_ACCEPT'] # => 'text/html,application/xhtml+xml,application/xml;q=0.9'accept?('text/html')# => trueaccept?('application/xml')# => trueaccept?('application/json')# => falseself.format# :html# @_env['HTTP_ACCEPT'] # => '*/*'accept?('text/html')# => trueaccept?('application/xml')# => trueaccept?('application/json')# => trueself.format# :htmlendend

Hanami::Controller is shipped with an extensive list of the most common MIME types. Also, you can register your own:

Hanami::Controller.configuredoformatcustom: 'application/custom'endclassIndexincludeHanami::Actiondefcall(params)endendaction=Index.newaction.call({'HTTP_ACCEPT'=>'application/custom'})# => Content-Type 'application/custom'action.format# => :customclassShowincludeHanami::Actiondefcall(params)# ...self.format=:customendendaction=Show.newaction.call({'HTTP_ACCEPT'=>'*/*'})# => Content-Type 'application/custom'action.format# => :custom

Streamed Responses

When the work to be done by the server takes time, it may be a good idea to stream your response. Here's an example of a streamed CSV.

Hanami::Controller.configuredoformatcsv: 'text/csv'middleware.use ::Rack::ChunkedendclassCsvincludeHanami::Actiondefcall(params)self.format=:csvself.body=Enumerator.newdo |yielder| yielder << csv_header# Expensive operation is streamed as each line becomes availablecsv_body.each_linedo |line| yielder << lineendendendend

Note:

  • In development, Hanami' code reloading needs to be disabled for streaming to work. This is because Shotgun interferes with the streaming action. You can disable it like this hanami server --code-reloading=false
  • Streaming does not work with WEBrick as it buffers its response. We recommend using puma, though you may find success with other servers

No rendering, please

Hanami::Controller is designed to be a pure HTTP endpoint, rendering belongs to other layers of MVC. You can set the body directly (see response), or use Hanami::View.

Controllers

A Controller is nothing more than a logical group of actions: just a Ruby module.

moduleArticlesclassIndexincludeHanami::Action# ...endclassShowincludeHanami::Action# ...endendArticles::Index.new.call({})

Hanami::Router integration

While Hanami::Router works great with this framework, Hanami::Controller doesn't depend on it. You, the developer, are free to choose your own routing system.

But, if you use them together, the only constraint is that an action must support arity 0 in its constructor. The following examples are valid constructors:

definitializeenddefinitialize(repository=ArticleRepository.new)enddefinitialize(repository: ArticleRepository.new)enddefinitialize(options={})enddefinitialize(*args)end

Please note that this is subject to change: we're working to remove this constraint.

Hanami::Router supports lazy loading for controllers. While this policy can be a convenient fallback, you should know that it's the slower option. Be sure of loading your controllers before you initialize the router.

Rack integration

Hanami::Controller is compatible with Rack. However, it doesn't mount any middleware. While a Hanami application's architecture is more web oriented, this framework is designed to build pure HTTP endpoints.

Rack middleware

Rack middleware can be configured globally in config.ru. However, consider that they often add unnecessary overhead for all endpoints that aren't direct users of all the configured middleware.

Think about a middleware to create sessions, where only SessionsController::Create needs that middleware, but every other action pays the performance price for that middleware.

The solution is that an action can employ one or more Rack middleware, with .use.

require'hanami/controller'moduleSessionsclassCreateincludeHanami::ActionuseOmniAuthdefcall(params)# ...endendend
require'hanami/controller'moduleSessionsclassCreateincludeHanami::ControlleruseXMiddleware.new('x',123)useYMiddleware.newuseZMiddlewaredefcall(params)# ...endendend

Configuration

Hanami::Controller can be configured with a DSL. It supports a few options:

require'hanami/controller'Hanami::Controller.configuredo# Handle exceptions with HTTP statuses (true) or don't catch them (false)# Argument: boolean, defaults to `true`#handle_exceptionstrue# If the given exception is raised, return that HTTP status# It can be used multiple times# Argument: hash, empty by default#handle_exceptionArgumentError=>404# Register a format to MIME type mapping# Argument: hash, key: format symbol, value: MIME type string, empty by default#formatcustom: 'application/custom'# Define a fallback format to detect in case of HTTP request with `Accept: */*`# If not defined here, it will return Rack's default: `application/octet-stream`# Argument: symbol, it should be already known. defaults to `nil`#default_request_format:html# Define a default format to set as `Content-Type` header for response,# unless otherwise specified.# If not defined here, it will return Rack's default: `application/octet-stream`# Argument: symbol, it should be already known. defaults to `nil`#default_response_format:html# Define a default charset to return in the `Content-Type` response header# If not defined here, it returns `utf-8`# Argument: string, defaults to `nil`#default_charset'koi8-r'# Configure the logic to be executed when Hanami::Action is included# This is useful to DRY code by having a single place where to configure# shared behaviors like authentication, sessions, cookies etc.# Argument: proc#preparedoincludeHanami::Action::SessionsincludeMyAuthenticationuseSomeMiddleWarebefore{authenticate!}endend

All of the global configurations can be overwritten at the controller level. Each controller and action has its own copy of the global configuration.

This means changes are inherited from the top to the bottom, but do not bubble back up.

require'hanami/controller'Hanami::Controller.configuredohandle_exceptionArgumentError=>400endmoduleArticlesclassCreateincludeHanami::Actionconfiguredohandle_exceptionsfalseenddefcall(params)raiseArgumentErrorendendendmoduleUsersclassCreateincludeHanami::Actiondefcall(params)raiseArgumentErrorendendendUsers::Create.new.call({})# => HTTP 400Articles::Create.new.call({})# => raises ArgumentError because we set handle_exceptions to false

Thread safety

An Action is mutable. When used without Hanami::Router, be sure to instantiate an action for each request. The same advice applies when using Hanami::Router but NOT routing to mycontroller#myaction but instead routing direct to a class.

# config.rurequire'hanami/controller'classActionincludeHanami::Actiondefself.call(env)new.call(env)enddefcall(params)self.body=object_id.to_sendendrunAction

Hanami::Controller heavely depends on class configuration. To ensure immutability in deployment environments, use Hanami::Controller.load!.

Versioning

Hanami::Controller uses Semantic Versioning 2.0.0

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Copyright

Copyright © 2014-2016 Luca Guidi – Released under MIT License

This project was formerly known as Lotus (lotus-controller).

About

Complete, fast and testable actions for Rack and Hanami

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby99.8%
  • Shell0.2%