Skip to content

Action Render + Rescue handlers for different MIME types in Rails

License

Notifications You must be signed in to change notification settings

ryancyq/mime_actor

Repository files navigation

mime_actor

Version CI Coverage Maintainability

Action Render + Rescue handlers for different MIME types in Rails

Usage

MimeActor allows you to do something like below:

class EventsController < ActionController::Base
    # AbstractController::Callbacks here to load model with params
    before_action only: :index { @events = Event.all }
    before_action only: [:show, :update] { @event = Event.find(params.require(:event_id)) }

    respond_act_to :html, :json, on: :index
    respond_act_to :html, :json, on: [:show, :update]

    rescue_act_from ActiveRecord::RecordNotFound, format: :json do |ex|
        render status: :bad_request, json: { error: "Resouce not found" }
    end

    rescue_act_from ActiveRecord::RecordNotFound, format: :html, action: :show do |ex|
        redirect_to events_path
    end

    def index_html
        @event_categories = EventCategory.all
        render :index # render html using @events and @event_categories
    end

    def index_json
        render json: @events # render json using #as_json
    end

    def show_html
        render :show # render html using @event
    end

    def update_html
        redirect_to event_path(@event.id) # redirect to show upon sucessful update
    rescue ActiveRecord::RecordNotFound
        render :edit
    end

    def show_json
        render json: @event # render json using #as_json
    end

    def update_json
        # ...
        render json: @event # render json using #as_json
    end
end

Seems useful? See the Comparison on how it can improve your existing code

Features

Documentation

You can find the documentation on RubyDoc.

Requirements

  • Ruby: MRI 3.1+
  • Rails: 5.0+

Installation

Install the gem and add to the application's Gemfile by executing:

bundle add mime_actor

If bundler is not being used to manage dependencies, install the gem by executing:

gem install mime_actor

Development

After checking out the repo, run bin/setup to install dependencies. Then, run bundle exec rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

License

Please see LICENSE for licensing details.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ryancyq/mime_actor.

About

Action Render + Rescue handlers for different MIME types in Rails

Topics

Resources

License

Stars

Watchers

Forks