Complete, fast, and testable actions for Rack and Hanami
- Home page: http://hanamirb.org
- Community: http://hanamirb.org/community
- Guides: https://guides.hanamirb.org
- Mailing List: http://hanamirb.org/mailing-list
- API Doc: http://rubydoc.info/gems/hanami-controller
- Chat: http://chat.hanamirb.org
Add this line to your application's Gemfile:
gem"hanami-controller"And then execute:
$ bundleOr install it yourself as:
$ gem install hanami-controllerHanami::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.
The core of this framework are the actions. They are the endpoints that respond to incoming HTTP requests.
classShow < Hanami::Actiondefhandle(request,response)response[:article]=ArticleRepository.new.find(request.params[:id])endendHanami::Action follows the Hanami philosophy: a single purpose object with a minimal interface.
In this case, Hanami::Action provides the key public interface of #call(env), making your actions Rack-compatible. To provide custom behaviour when your actions are being called, you can implement #handle(request, response)
An action is an object and you have full control over 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.
classShow < Hanami::Actiondefinitialize(configuration:,repository: ArticleRepository.new)@repository=repositorysuper(configuration: configuration)enddefhandle(request,response)response[:article]=repository.find(request.params[:id])endprivateattr_reader:repositoryendconfiguration=Hanami::Controller::Configuration.newaction=Show.new(configuration: configuration,repository: ArticleRepository.new)action.call(id: 23)The request params are part of the request passed as an argument to the #handle method. If routed with Hanami::Router, it extracts the relevant bits from the Rack env (e.g. 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:
classShow < Hanami::Actiondefhandle(request, *)# ...putsrequest.params# =>{id: 23 } extracted from Rack envendendStandalone:
classShow < Hanami::Actiondefhandle(request, *)# ...putsrequest.params# =>{:"rack.version"=>[1, 2], :"rack.input"=>#<StringIO:0x007fa563463948>, ... }endendUnit Testing:
classShow < Hanami::Actiondefhandle(request, *)# ...putsrequest.params# =>{id: 23, key: "value" } passed as it is from testingendendaction=Show.new(configuration: configuration)response=action.call(id: 23,key: "value")Params represent an untrusted input. For security reasons it's recommended to allowlist them.
require"hanami/validations"require"hanami/controller"classSignup < Hanami::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?)endenddefhandle(request, *)# Describe inheritance hierarchyputsrequest.params.class# => Signup::Paramsputsrequest.params.class.superclass# => Hanami::Action::Params# Allowlist :first_name, but not :adminputsrequest.params[:first_name]# => "Luca"putsrequest.params[:admin]# => nil# Allowlist nested params [:address][:line_one], not [:address][:line_two]putsrequest.params[:address][:line_one]# => "69 Tender St"putsrequest.params[:address][:line_two]# => nilendendBecause 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"classSignup < Hanami::ActionMEGABYTE=1024 ** 2paramsdorequired(:first_name).filled(:str?)required(:last_name).filled(:str?)required(:email).filled?(:str?,format?: /\A.+@.+\z/)required(:password).filled(:str?).confirmationrequired(:terms_of_service).filled(:bool?)required(:age).filled(:int?,included_in?: 18..99)optional(:avatar).filled(size?: 1..(MEGABYTE * 3))enddefhandle(request, *)halt400unlessrequest.params.valid?# ...endendThe output of #call is a Hanami::Action::Response:
classShow < Hanami::Actionendaction=Show.new(configuration: configuration)action.call({})# => #<Hanami::Action::Response:0x00007fe8be968418 @status=200 ...>This is the same response object passed to #handle, where you can use its accessors to explicitly set status, headers, and body:
classShow < Hanami::Actiondefhandle(*,response)response.status=201response.body="Hi!"response.headers.merge!("X-Custom"=>"OK")endendaction=Show.newaction.call({})# => [201,{"X-Custom" => "OK" }, ["Hi!"]]In case you need to send data from the action to other layers of your application, you can use exposures. By default, an action exposes the received params.
classShow < Hanami::Actiondefhandle(request,response)response[:article]=ArticleRepository.new.find(request.params[:id])endendaction=Show.new(configuration: configuration)response=action.call(id: 23)article=response[:article]article.class# => Articlearticle.id# => 23response.exposures.keys# => [:params, :article]If you need to execute logic before or after#handle is invoked, you can use callbacks. They are useful for shared logic like authentication checks.
classShow < Hanami::Actionbefore:authenticate,:set_articledefhandle(*)endprivatedefauthenticate# ...end# `request` and `response` in the method signature is optionaldefset_article(request,response)response[:article]=ArticleRepository.new.find(request.params[:id])endendCallbacks can also be expressed as anonymous lambdas:
classShow < Hanami::Actionbefore{ ... }# do some authentication stuffbefore{ |request,response| response[:article]=ArticleRepository.new.find(request.params[:id])}defhandle(*)endendWhen the app raises an exception, hanami-controller, does NOT manage it. You can write custom exception handling on per action or configuration basis.
An exception handler can be a valid HTTP status code (eg. 500, 401), or a Symbol that represents an action method.
classShow < Hanami::Actionhandle_exceptionStandardError=>500defhandle(*)raiseendendaction=Show.new(configuration: configuration)action.call({})# => [500,{}, ["Internal Server Error"]]You can map a specific raised exception to a different HTTP status.
classShow < Hanami::Actionhandle_exceptionRecordNotFound=>404defhandle(*)raiseRecordNotFoundendendaction=Show.new(configuration: configuration)action.call({})# => [404,{}, ["Not Found"]]You can also define custom handlers for exceptions.
classCreate < Hanami::Actionhandle_exceptionArgumentError=>:my_custom_handlerdefhandle(*)raiseArgumentError.new("Invalid arguments")endprivatedefmy_custom_handler(request,response,exception)response.status=400response.body=exception.messageendendaction=Create.new(configuration: configuration)action.call({})# => [400,{}, ["Invalid arguments"]]Exception policies can be defined globally via configuration:
configuration=Hanami::Controller::Configuration.newdo |config| config.handle_exceptionRecordNotFound=>404endclassShow < Hanami::Actiondefhandle(*)raiseRecordNotFoundendendaction=Show.new(configuration: configuration)action.call({})# => [404,{}, ["Not Found"]]classMyCustomException < StandardErrorendmoduleArticlesclassIndex < Hanami::Actionhandle_exceptionMyCustomException=>:handle_my_exceptiondefhandle(*)raiseMyCustomExceptionendprivatedefhandle_my_exception(request,response,exception)# ...endendclassShow < Hanami::Actionhandle_exceptionStandardError=>:handle_standard_errordefhandle(*)raiseMyCustomExceptionendprivatedefhandle_standard_error(request,response,exception)# ...endendendArticles::Index.new.call({})# => `handle_my_exception` will be invokedArticles::Show.new.call({})# => `handle_standard_error` will be invoked,# because `MyCustomException` inherits from `StandardError`When #halt is used with a valid HTTP code, it stops the execution and sets the proper status and body for the response:
classShow < Hanami::Actionbefore:authenticate!defhandle(*)# ...endprivatedefauthenticate!halt401unlessauthenticated?endendaction=Show.new(configuration: configuration)action.call({})# => [401,{}, ["Unauthorized"]]Alternatively, you can specify a custom message.
classShow < Hanami::Actiondefhandle(request,response)response[:droid]=DroidRepository.new.find(request.params[:id])ornot_foundendprivatedefnot_foundhalt404,"This is not the droid you're looking for"endendaction=Show.new(configuration: configuration)action.call({})# => [404,{}, ["This is not the droid you're looking for"]]You can read the original cookies sent from the HTTP client via request.cookies. If you want to send cookies in the response, use response.cookies.
They are read as a Hash from Rack env:
require"hanami/controller"require"hanami/action/cookies"classReadCookiesFromRackEnv < Hanami::ActionincludeHanami::Action::Cookiesdefhandle(request, *)# ...request.cookies[:foo]# => "bar"endendaction=ReadCookiesFromRackEnv.new(configuration: configuration)action.call({"HTTP_COOKIE"=>"foo=bar"})They are set like a Hash:
require"hanami/controller"require"hanami/action/cookies"classSetCookies < Hanami::ActionincludeHanami::Action::Cookiesdefhandle(*,response)# ...response.cookies[:foo]="bar"endendaction=SetCookies.new(configuration: configuration)action.call({})# => [200,{"Set-Cookie" => "foo=bar"}, "..."]They are removed by setting their value to nil:
require"hanami/controller"require"hanami/action/cookies"classRemoveCookies < Hanami::ActionincludeHanami::Action::Cookiesdefhandle(*,response)# ...response.cookies[:foo]=nilendendaction=RemoveCookies.new(configuration: configuration)action.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 overridden case by case.
require"hanami/controller"require"hanami/action/cookies"configuration=Hanami::Controller::Configuration.newdo |config| config.cookies(max_age: 300)# 5 minutesendclassSetCookies < Hanami::ActionincludeHanami::Action::Cookiesdefhandle(*,response)# ...response.cookies[:foo]={value: "bar",max_age: 100}endendaction=SetCookies.new(configuration: configuration)action.call({})# => [200,{"Set-Cookie" => "foo=bar; max-age=100;"}, "..."]Actions have builtin support for Rack sessions. Similarly to cookies, you can read the session sent by the HTTP client via request.session, and also manipulate it via response.session.
require"hanami/controller"require"hanami/action/session"classReadSessionFromRackEnv < Hanami::ActionincludeHanami::Action::Sessiondefhandle(request, *)# ...request.session[:age]# => "35"endendaction=ReadSessionFromRackEnv.new(configuration: configuration)action.call({"rack.session"=>{"age"=>"35"}})Values can be set like a Hash:
require"hanami/controller"require"hanami/action/session"classSetSession < Hanami::ActionincludeHanami::Action::Sessiondefhandle(*,response)# ...response.session[:age]=31endendaction=SetSession.new(configuration: configuration)action.call({})# => [200,{"Set-Cookie"=>"rack.session=..."}, "..."]Values can be removed like a Hash:
require"hanami/controller"require"hanami/action/session"classRemoveSession < Hanami::ActionincludeHanami::Action::Sessiondefhandle(*,response)# ...response.session[:age]=nilendendaction=RemoveSession.new(configuration: configuration)action.call({})# => [200,{"Set-Cookie"=>"rack.session=..."}, "..."] it removes that value from the sessionWhile 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(configuration: configuration)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"classHttpCacheController < Hanami::ActionincludeHanami::Action::Cachecache_control:public,max_age: 600# => Cache-Control: public, max-age=600defhandle(*)# ...endendExpires header can be specified using expires method:
require"hanami/controller"require"hanami/action/cache"classHttpCacheController < Hanami::ActionincludeHanami::Action::Cacheexpires60,:public,max_age: 600# => Expires: Sun, 03 Aug 2014 17:47:02 GMT, Cache-Control: public, max-age=600defhandle(*)# ...endendAccording 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 304 (Not Modified) response.
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"classConditionalGetController < Hanami::ActionincludeHanami::Action::Cachedefhandle(*)# ...freshetag: resource.cache_key# => halt 304 with header IfNoneMatch = resource.cache_keyendendIf resource.cache_key is equal to IfNoneMatch header, then hanami will halt 304.
An alternative to hashing based check, is the time based check:
require"hanami/controller"require"hanami/action/cache"classConditionalGetController < Hanami::ActionincludeHanami::Action::Cachedefhandle(*)# ...freshlast_modified: resource.updated_at# => halt 304 with header IfModifiedSince = resource.updated_at.httpdateendendIf resource.updated_at is equal to IfModifiedSince header, then hanami will halt 304.
If you need to redirect the client to another resource, use response.redirect_to:
classCreate < Hanami::Actiondefhandle(*,response)# ...response.redirect_to"http://example.com/articles/23"endendaction=Create.new(configuration: configuration)action.call({article: {title: "Hello"}})# => [302,{"Location" => "/articles/23"}, ""]You can also redirect with a custom status code:
classCreate < Hanami::Actiondefhandle(*,response)# ...response.redirect_to"http://example.com/articles/23",status: 301endendaction=Create.new(configuration: configuration)action.call({article: {title: "Hello"}})# => [301,{"Location" => "/articles/23"}, ""]Hanami::Action automatically sets the Content-Type header, according to the request.
classShow < Hanami::Actiondefhandle(*)endendaction=Show.new(configuration: configuration)response=action.call({"HTTP_ACCEPT"=>"*/*"})# Content-Type "application/octet-stream"response.format# :allresponse=action.call({"HTTP_ACCEPT"=>"text/html"})# Content-Type "text/html"response.format# :htmlHowever, you can force this value:
classShow < Hanami::Actiondefhandle(*,response)# ...response.format=:jsonendendaction=Show.new(configuration: configuration)response=action.call({"HTTP_ACCEPT"=>"*/*"})# Content-Type "application/json"response.format# :jsonresponse=action.call({"HTTP_ACCEPT"=>"text/html"})# Content-Type "application/json"response.format# :jsonYou can restrict the accepted MIME types:
classShow < Hanami::Actionaccept:html,:jsondefhandle(*)# ...endend# When called with "*/*" => 200# When called with "text/html" => 200# When called with "application/json" => 200# When called with "application/xml" => 415You can check if the requested MIME type is accepted by the client.
classShow < Hanami::Actiondefhandle(request,response)# ...# @_env["HTTP_ACCEPT"] # => "text/html,application/xhtml+xml,application/xml;q=0.9"request.accept?("text/html")# => truerequest.accept?("application/xml")# => truerequest.accept?("application/json")# => falseresponse.format# :html# @_env["HTTP_ACCEPT"] # => "*/*"request.accept?("text/html")# => truerequest.accept?("application/xml")# => truerequest.accept?("application/json")# => trueresponse.format# :htmlendendHanami::Controller is shipped with an extensive list of the most common MIME types. Also, you can register your own:
configuration=Hanami::Controller::Configuration.newdo |config| config.formatcustom: "application/custom"endclassIndex < Hanami::Actiondefhandle(*)endendaction=Index.new(configuration: configuration)response=action.call({"HTTP_ACCEPT"=>"application/custom"})# => Content-Type "application/custom"response.format# => :customclassShow < Hanami::Actiondefhandle(*,response)# ...response.format=:customendendaction=Show.new(configuration: configuration)response=action.call({"HTTP_ACCEPT"=>"*/*"})# => Content-Type "application/custom"response.format# => :customWhen 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.
configuration=Hanami::Controller::Configuration.newdo |config| config.formatcsv: 'text/csv'endclassCsv < Hanami::Actiondefhandle(*,response)response.format=:csvresponse.body=Enumerator.newdo |yielder| yielder << csv_header# Expensive operation is streamed as each line becomes availablecsv_body.each_linedo |line| yielder << lineendendendendNote:
- In development, Hanami' code reloading needs to be disabled for streaming to work. This is because
Shotguninterferes with the streaming action. You can disable it like thishanami 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
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.
A Controller is nothing more than a logical group of actions: just a Ruby module.
moduleArticlesclassIndex < Hanami::Action# ...endclassShow < Hanami::Action# ...endendArticles::Index.new(configuration: configuration).call({})require"hanami/router"require"hanami/controller"moduleWebmoduleControllersmoduleBooksclassShow < Hanami::Actiondefhandle(*)endendendendendconfiguration=Hanami::Controller::Configuration.newrouter=Hanami::Router.new(configuration: configuration,namespace: Web::Controllers)doget"/books/:id","books#show"endHanami::Controller is compatible with Rack. If you need to use any Rack middleware, please mount them in config.ru.
Hanami::Controller can be configured via Hanami::Controller::Configuration. It supports a few options:
require"hanami/controller"configuration=Hanami::Controller::Configuration.newdo |config| # If the given exception is raised, return that HTTP status# It can be used multiple times# Argument: hash, empty by default#config.handle_exceptionArgumentError=>404# Register a format to MIME type mapping# Argument: hash, key: format symbol, value: MIME type string, empty by default#config.formatcustom: "application/custom"# 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`#config.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`#config.default_charset="koi8-r"endAn Action is immutable, it works without global state, so it's thread-safe by design.
Hanami::Controller uses Semantic Versioning 2.0.0
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
Copyright © 2014–2024 Hanami Team – Released under MIT License