Giter Site home page Giter Site logo

heartcombo / responders Goto Github PK

View Code? Open in Web Editor NEW
2.0K 35.0 155.0 430 KB

A set of Rails responders to dry up your application

Home Page: http://blog.plataformatec.com.br/

License: MIT License

Ruby 99.76% HTML 0.21% JavaScript 0.03%
ruby rails flash-messages controllers

responders's Introduction

Responders

Gem Version

A set of responders modules to dry up your Rails app.

Installation

Add the responders gem to your Gemfile:

gem "responders"

Update your bundle and run the install generator:

$ bundle install
$ rails g responders:install

If you are including this gem to support backwards compatibility for responders in previous releases of Rails, you only need to include the gem and bundle.

$ bundle install

Responders Types

FlashResponder

Sets the flash based on the controller action and resource status. For instance, if you do: respond_with(@post) on a POST request and the resource @post does not contain errors, it will automatically set the flash message to "Post was successfully created" as long as you configure your I18n file:

  flash:
    actions:
      create:
        notice: "%{resource_name} was successfully created."
      update:
        notice: "%{resource_name} was successfully updated."
      destroy:
        notice: "%{resource_name} was successfully destroyed."
        alert: "%{resource_name} could not be destroyed."

In case the resource contains errors, you should use the failure key on I18n. This is useful to dry up flash messages from your controllers. Note: by default alerts for update and destroy actions are commented in generated I18n file. If you need a specific message for a controller, let's say, for PostsController, you can also do:

  flash:
    posts:
      create:
        notice: "Your post was created and will be published soon"

This responder is activated in all non get requests. By default it will use the keys :notice and :alert, but they can be changed in your application:

config.responders.flash_keys = [ :success, :failure ]

You can also have embedded HTML. Just create a _html scope.

  flash:
    actions:
      create:
        alert_html: "<strong>OH NOES!</strong> You did it wrong!"
    posts:
      create:
        notice_html: "<strong>Yay!</strong> You did it!"

See also the namespace_lookup option to search the full hierarchy of possible keys.

HttpCacheResponder

Automatically adds Last-Modified headers to API requests. This allows clients to easily query the server if a resource changed and if the client tries to retrieve a resource that has not been modified, it returns not_modified status.

CollectionResponder

Makes your create and update action redirect to the collection on success.

LocationResponder

This responder allows you to use callable objects as the redirect location. Useful when you want to use the respond_with method with a custom route that requires persisted objects, but the validation may fail.

Note: this responder is included by default, and doesn't need to be included on the top of your controller (including it will issue a deprecation warning).

class ThingsController < ApplicationController
  respond_to :html

  def create
    @thing = Thing.create(params[:thing])
    respond_with @thing, location: -> { thing_path(@thing) }
  end
end

Dealing with namespaced routes

In order for the LocationResponder to find the correct route helper for namespaced routes you need to pass the namespaces to respond_with:

class Api::V1::ThingsController < ApplicationController
  respond_to :json

  # POST /api/v1/things
  def create
    @thing = Thing.create(thing_params)
    respond_with :api, :v1, @thing
  end
end

Configuring your own responder

Responders only provides a set of modules and to use them you have to create your own responder. After you run the install command, the following responder will be generated in your application:

# lib/application_responder.rb
class ApplicationResponder < ActionController::Responder
  include Responders::FlashResponder
  include Responders::HttpCacheResponder
end

Your application also needs to be configured to use it:

# app/controllers/application_controller.rb
require "application_responder"

class ApplicationController < ActionController::Base
  self.responder = ApplicationResponder
  respond_to :html
end

Controller method

This gem also includes the controller method responders, which allows you to cherry-pick which responders you want included in your controller.

class InvitationsController < ApplicationController
  responders :flash, :http_cache
end

Interpolation Options

You can pass in extra interpolation options for the translation by adding an flash_interpolation_options method to your controller:

class InvitationsController < ApplicationController
  responders :flash, :http_cache

  def create
    @invitation = Invitation.create(params[:invitation])
    respond_with @invitation
  end

  private

  def flash_interpolation_options
    { resource_name: @invitation.email }
  end
end

Now you would see the message "[email protected] was successfully created" instead of the default "Invitation was successfully created."

Generator

This gem also includes a responders controller generator, so your scaffold can be customized to use respond_with instead of default respond_to blocks. From 2.1, you need to explicitly opt-in to use this generator by adding the following to your config/application.rb:

config.app_generators.scaffold_controller :responders_controller

Failure handling

Responders don't use valid? to check for errors in models to figure out if the request was successful or not, and relies on your controllers to call save or create to trigger the validations.

def create
  @widget = Widget.new(widget_params)
  # @widget will be a valid record for responders, as we haven't called `save`
  # on it, and will always redirect to the `widgets_path`.
  respond_with @widget, location: -> { widgets_path }
end

Responders will check if the errors object in your model is empty or not. Take this in consideration when implementing different actions or writing test assertions on this behavior for your controllers.

def create
  @widget = Widget.new(widget_params)
  @widget.errors.add(:base, :invalid)
  # `respond_with` will render the `new` template again,
  # and set the status based on the configured `error_status`.
  respond_with @widget
end

Verifying request formats

respond_with will raise an ActionController::UnknownFormat if the request MIME type was not configured through the class level respond_to, but the action will still be executed and any side effects (like creating a new record) will still occur. To raise the UnknownFormat exception before your action is invoked you can set the verify_requested_format! method as a before_action on your controller.

class WidgetsController < ApplicationController
  respond_to :json
  before_action :verify_requested_format!

  # POST /widgets.html won't reach the `create` action.
  def create
    widget = Widget.create(widget_params)
    respond_with widget
  end
end

Configuring error and redirect statuses

By default, respond_with will respond to errors on HTML & JS requests using the HTTP status code 200 OK, and perform redirects using the HTTP status code 302 Found, both for backwards compatibility reasons.

You can configure this behavior by setting config.responders.error_status and config.responders.redirect_status to the desired status codes.

config.responders.error_status = :unprocessable_entity
config.responders.redirect_status = :see_other

These can also be set in your custom ApplicationResponder if you have generated one: (see install instructions)

class ApplicationResponder < ActionController::Responder
  self.error_status = :unprocessable_entity
  self.redirect_status = :see_other
end

Note: the application responder generated for new apps already configures a different set of defaults: 422 Unprocessable Entity for errors, and 303 See Other for redirects. Responders may change the defaults to match these in a future major release.

Hotwire/Turbo and fetch APIs

Hotwire/Turbo expects successful redirects after form submissions to respond with HTTP status 303 See Other, and error responses to be 4xx or 5xx statuses, for example 422 Unprocessable Entity for displaying form validation errors and 500 Internal Server Error for other server errors. Turbo documentation: Redirecting After a Form Submission.

The example configuration showed above matches the statuses that better integrate with Hotwire/Turbo.

Examples

Want more examples ? Check out these blog posts:

Supported Ruby / Rails versions

We intend to maintain support for all Ruby / Rails versions that haven't reached end-of-life.

For more information about specific versions please check Ruby and Rails maintenance policies, and our test matrix.

Bugs and Feedback

If you discover any bugs or want to drop a line, feel free to create an issue on GitHub.

MIT License. Copyright 2020-2024 Rafael França, Carlos Antônio da Silva. Copyright 2009-2019 Plataformatec.

responders's People

Contributors

byroot avatar carlosantoniodasilva avatar deivid-rodriguez avatar elod avatar endeepak avatar excid3 avatar fnando avatar fudoshiki avatar georgeguimaraes avatar iain avatar jfeaver avatar josevalim avatar lucasmazza avatar marcandre avatar marcelocajueiro avatar matthewrudy avatar maxcal avatar mibamur avatar mikhail-alhimik avatar mracos avatar nashby avatar niklas avatar olivierlacan avatar pauloschiavon avatar petergoldstein avatar pravi avatar rafaelfranca avatar spectator avatar tegon avatar twe4ked avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

responders's Issues

FlashResponder for Json

Hi, I am using backbone and I want backbone app to set flash messages along with data.
But right now FlashResponder currently sets flash messages only for html and js

def to_html
  set_flash_message! if set_flash_message?
  super
end

def to_js
  set_flash_message! if set_flash_message?
  defined?(super) ? super : to_format
end

Is it possible for me to make FlashResponder to generate flash messages even for backbone ajax json requests?

def create
  @city = City.new(params[:city])
  @city.save
  respond_with @city  
end

multiple messages. choose at random?

Maybe a strange question.. I'd like to have multiple options for each kind of message, i.e.

flash:
    actions:
      destroy:
        notice: "{resource_name} was successfully destroyed, hopefully you meant to do that"
        notice: "{resource_name} was successfully destroyed. It's now gone forever."
        notice: "{resource_name} was successfully destroyed. Congrats."

.. and then have a version of the notice picked randomly. Is there a way of doing this?

rspec faillures (rspec-rails generated tests)

Failures:

  1. ProductsController POST create with invalid params re-renders the 'new' template
    Failure/Error: response.should render_template("new")
    expecting <"new"> but rendering with <"">

    ./spec/controllers/products_controller_spec.rb:100:in `block (4 levels) in <top (required)>'

Failures:

  1. ProductsController POST create with invalid params re-renders the 'new' template
    Failure/Error: response.should render_template("new")
    expecting <"new"> but rendering with <"">

    ./spec/controllers/products_controller_spec.rb:100:in `block (4 levels) in <top (required)>'

  2. ProductsController PUT update with invalid params re-renders the 'edit' template
    Failure/Error: response.should render_template("edit")
    expecting <"edit"> but rendering with <"">

    ./spec/controllers/products_controller_spec.rb:144:in `block (4 levels) in <top (required)>'

Finished in 0.77526 seconds
30 examples, 2 failures, 2 pending

Failed examples:

rspec ./spec/controllers/products_controller_spec.rb:96 # ProductsController POST create with invalid params re-renders the 'new' template
rspec ./spec/controllers/products_controller_spec.rb:139 # ProductsController PUT update with invalid params re-renders the 'edit' template
2) ProductsController PUT update with invalid params re-renders the 'edit' template
Failure/Error: response.should render_template("edit")
expecting <"edit"> but rendering with <"">
# ./spec/controllers/products_controller_spec.rb:144:in `block (4 levels) in <top (required)>'

Finished in 0.77526 seconds
30 examples, 2 failures, 2 pending

Failed examples:

rspec ./spec/controllers/products_controller_spec.rb:96 # ProductsController POST create with invalid params re-renders the 'new' template
rspec ./spec/controllers/products_controller_spec.rb:139 # ProductsController PUT update with invalid params re-renders the 'edit' template

Show only notices or only alerts

Hi,

I'd like to be able to configure responder in one controller to show only alerts and disable notices. I've tried 'notice: false/""nil' but it doesn't work and 'flash: false' disables alerts as well.

Thanks.

Used with inherited resources

Inherited resource gem says that to use flash message you must use the responders gem, i'm trying to have the errors from validation displayed in the flash message. Here is my controller action :

def update
    @produit=Produit.visible_to(current_shop).find(params[:id])
    update! do |success, failure|
      success.html { redirect_to edit_backend_produit_path(@produit) }
    end
  end

How do i modify it to display the errors in case of failure?

Flash messages not rendering through respond_with

I'm running rails edge on ruby 1.9.2dev and using the responders gem from the git master branch via bundler. I have a few RESTful controllers with actions like this:

def create
  @manga = Manga.new(params[:manga])
  @manga.save

  respond_with @manga, :notice => "Manga has been created successfully."
end

The :notice on respond_with is just for demonstration, sadly both fail to generate a flash message. Setting the flash hash manually works fine, so I'm inclined to believe I've either found a bug (or more likely) misconfigured the responders gem somehow.

Additionally, I have no custom configurations for responders and installed the gem by running the responders_install generator with bundle exec rails g responders_install.

Thanks in advance for any assistance you're willing to provide. I have the sneaking suspicion this is most likely a misconfiguration of some sort on my part.

Should the nested i18n lookup in FlashResponder be deprecated?

Since Rails doesn't support the nested i18n lookup for model translations anymore, would it make sense to deprecate and then remove it from FlashResponder as well?

I.e. so that messages for Admin::CarsController controller are fetched from flash.admin/cars.create.status instead of flash.admin.cars.create.status

CollectionResponder with inflect.uncountable

I have:

  • resources :news (in admin namespace)
  • inflect.uncountable %w[ news ]
  • respond_with :admin, @news

rake routes:
admin_news_index GET /admin/news(.:format) web/admin/news#index
admin_news GET /admin/news/:id(.:format) web/admin/news#show

ActionController::RoutingError: No route matches {:action=>"show", :controller=>"web/admin/news"}
because url is admin_news instead admin_news_index

Typo in README.doc

In the documentation, there's a small typo in the I18n translations for FlashResponder. Interpolated values should be in double brackets:

flash:
  actions:
    create:
      notice: "{{resource_name}} was successfully created"
    update:
      notice: "{{resource_name}} was successfully updated"
    destroy:
      alert: "{{resource_name}} could not be destroyed"

Rails 3 Edge railties change error

Now getting:

"undefined method `responders` for #<Rails::Railtie::Configuration:0x46cad00> (NoMethodError)"

from

lib/responders.rb:20

on edge rails.

Rails3.0.0.beta3 NameError: uninitialized constant FlashResponder

When trying to use a responder through responders :flash I get an uninitialized constant.
It works when I write responder Responder::FlashResponder.

responders :flash works when I change line 25 of controller_method.rb from:
"#{responder.to_s.classify}Responder".constantize" to:
"Responders::#{responder.to_s.classify}Responder".constantize

Customize controller template

Hi,

I tried to customize the controller template by overriding it in lib/templates/rails/scaffold_controller/controller.rb. Unfortunately it does not work as it seems that responders does not take it into account.

Using Rails 3.1rc5 I created a new app, generated a scaffold with the custom controller and it worked. Then I removed the stuff and installed responders. I generated the scaffold and the custom controller was not taken into account. After removing responders it worked well again.

Hope it helps.

FlashResponder not working in Rails 4.1.0-beta1

It seems to be ignoring the ApplicationController#to_html method.

Snip of the backtrace starting at ActionController:

--> #0  ProfilesController.update at /Users/anders/Desktop/appname/app/controllers/profiles_controller.rb:12
    #1  ActionController::ImplicitRender.send_action(method#String, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/implicit_render.rb:4
    #2  AbstractController::Base.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/abstract_controller/base.rb:189
    #3  ActionController::Rendering.process_action(action#NilClass, *args#NilClass) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/rendering.rb:8
    #4  block in AbstractController::Callbacks.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/abstract_controller/callbacks.rb:20
     ͱ-- #5  Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:113
    #6  ActiveSupport::Callbacks::Filters::End.call(env#ActiveSupport::Callbacks::Filters::Environment) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:113
    #7  block in #<Class:ActiveSupport::Callbacks::Filters::Before>.halting(next_callback#ActiveSupport::Callbacks::Filters::End, user_callback#Proc, halted_lambda#Proc, filter#Proc)
      at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
     ͱ-- #8  Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
    #9  block in #<Class:ActiveSupport::Callbacks::Filters::Before>.halting(next_callback#Proc, user_callback#Proc, halted_lambda#Proc, filter#Proc) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
     ͱ-- #10 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
    #11 block in #<Class:ActiveSupport::Callbacks::Filters::After>.halting(next_callback#Proc, user_callback#Proc) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
     ͱ-- #12 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
    #13 block in #<Class:ActiveSupport::Callbacks::Filters::After>.halting(next_callback#Proc, user_callback#Proc) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
     ͱ-- #14 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
    #15 block in #<Class:ActiveSupport::Callbacks::Filters::Before>.halting(next_callback#Proc, user_callback#Proc, halted_lambda#Proc, filter#Symbol) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
     ͱ-- #16 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
    #17 block in #<Class:ActiveSupport::Callbacks::Filters::Before>.halting(next_callback#Proc, user_callback#Proc, halted_lambda#Proc, filter#Symbol) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
     ͱ-- #18 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
    #19 block in #<Class:ActiveSupport::Callbacks::Filters::After>.halting(next_callback#Proc, user_callback#Proc) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:229
     ͱ-- #20 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
    #21 block in #<Class:ActiveSupport::Callbacks::Filters::Before>.halting(next_callback#Proc, user_callback#Proc, halted_lambda#Proc, filter#Symbol) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:166
     ͱ-- #22 Proc.call(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:86
    #23 ActiveSupport::Callbacks.run_callbacks(kind#Symbol, &block#Proc) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/callbacks.rb:86
    #24 AbstractController::Callbacks.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/abstract_controller/callbacks.rb:19
    #25 ActionController::Rescue.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/rescue.rb:29
    #26 block in ActionController::Instrumentation.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/instrumentation.rb:31
    #27 block in #<Class:ActiveSupport::Notifications>.instrument(name#String, payload#Hash) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/notifications.rb:159
    #28 ActiveSupport::Notifications::Instrumenter.instrument(name#String, payload#Hash) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/notifications/instrumenter.rb:20
    #29 #<Class:ActiveSupport::Notifications>.instrument(name#String, payload#Hash) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activesupport-4.1.0.beta2/lib/active_support/notifications.rb:159
    #30 ActionController::Instrumentation.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/instrumentation.rb:30
    #31 ActionController::ParamsWrapper.process_action(action#NilClass, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/params_wrapper.rb:245
    #32 ActiveRecord::Railties::ControllerRuntime.process_action(action#String, *args#Array) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/activerecord-4.1.0.beta2/lib/active_record/railties/controller_runtime.rb:18
    #33 AbstractController::Base.process(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/abstract_controller/base.rb:136
    #34 ActionView::Rendering.process(*args) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionview-4.1.0.beta2/lib/action_view/rendering.rb:30
    #35 ActionController::Metal.dispatch(action#NilClass, request#ActionDispatch::Request) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal.rb:195
    #36 ActionController::RackDelegation.dispatch(action#String, request#ActionDispatch::Request) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal/rack_delegation.rb:13
    #37 block in #<Class:ActionController::Metal>.action(name#String, klass#Class) at /Users/anders/.rvm/gems/ruby-2.1.0/gems/actionpack-4.1.0.beta2/lib/action_controller/metal.rb:231

accentuated characters causes message lost for flashresponders

Given this configuration

en:
  flash:
      pages:
        create:
          notice: "Page was successfully created."
          alert: "Page was not created."

If I change the message for the french part in : "Page créée avec succès."

The flash is not sent back.
This happens with rails 3.2.8. and responders 0.9.2

Is it something that is missing in my configuration file or yaml file?

not displayed flash

I use (responders-1.0.0, ruby 1.9.2. rails 3.2.14).
My code:

class AdsController < ApplicationController
  %(reject send_ad).each do |event|
      define_method(event) do
        @ad.send(event)
        respond_with @ad do |format|
          format.html { redirect_to ad_path }
        end
      end
    end
end

My responders.em.yml

en:
  flash:
    actions:
      create:
        notice: '%{resource_name} was successfully created.'
        alert: '%{resource_name} could not be created.'
      update:
        notice: '%{resource_name} was successfully updated.'
        alert: '%{resource_name} could not be updated.'
      destroy:
        notice: '%{resource_name} was successfully destroyed.'
        alert: '%{resource_name} could not be destroyed.'
      destroy_collection:
        notice: ' were destroyed.'
        alert: ' were not destroyed.'
      reject:
        notice: 'test'
        alert: 'testttttt'
      send_ad:
        notice: 'test'
        alert: 'testttttt'

why does not appear flash?

responders_controller doesn’t work when configured in application.rb

I have:

config.generators do |g|
  g.scaffold :scaffold_controller => :responders_controller
end

in +application.rb+ and responders_controller generator does not found:

$ ./script/generate scaffold Article
   invoke  active_record
   create    db/migrate/20100123033403_create_articles.rb
   create    app/models/article.rb
   invoke    test_unit
   create      test/unit/article_test.rb
   invoke      factory_girl
   create        test/factories/articles.rb
    route  resources :articles
    error  responders_controller [not found]
   invoke  stylesheets
identical    public/stylesheets/scaffold.css

But if I generate just responders_generator — it works!

$ ./script/generate responders_controller Article
create  app/controllers/articles_controller.rb
invoke  haml
create    app/views/articles
create    app/views/articles/index.html.haml
create    app/views/articles/edit.html.haml
create    app/views/articles/show.html.haml
create    app/views/articles/new.html.haml
create    app/views/articles/_form.html.haml
create    app/views/layouts/articles.html.haml
invoke  test_unit
create    test/functional/articles_controller_test.rb
invoke  helper
create    app/helpers/articles_helper.rb
invoke    test_unit
create      test/unit/helpers/articles_helper_test.rb

How to made it work? (I have already changed require path in responders_controller_generator to correspond new rails generators’ paths )

Using Rails 2.3.5, InheritedResources, and RSpec/Webrat - flash messages don't render in test env.

There's a sample app at: http://github.com/mattvanhorn/foobar that shows this.
Run the app, and go to widgets/new - create a widget and see the normal flash success message.

However, run this test:

describe "Widgets" do
  it "shows a success message on successful create" do
    visit widgets_path
    click_link "New widget"
    fill_in "Name", :with => "FooBarBaz"
    click_button "Create"    
    response.body.should include('Widget was successfully created.')
  end
end

and it will fail.

This test passed when I was on bundler 0.9.5, but it seems more directly related to Responder.

no such file to load -- generators/rails/scaffold_controller/scaffold_controller_generator

inbox zero? Here we go :)

rails g scaffold Post name:string description:text

/home/jo/.bundle/ruby/1.8/bundler/gems/rails-16a5e918a06649ffac24fd5873b875daf66212ad-master/activesupport/lib/active_support/dependencies.rb:209:in `require': no such file to load -- generators/rails/scaffold_controller/scaffold_controller_generator (LoadError)
...
from /home/jo/.bundle/ruby/1.8/bundler/gems/inherited_resources-521d1603ff4f7c4370007a37f86d32f24d49b322-master/lib/generators/rails/inherited_resources_controller_generator.rb:1

Greetings
Johannes

Problem scaffold

why this error is occurring on the scaffold?

When I disable the gem in Gemfile of responders, works normal.

rails g scaffold task message:text finally_in:datetime 
      invoke  active_record
      create    db/migrate/20140703005110_create_tasks.rb
      create    app/models/task.rb
      invoke    test_unit
      create      test/models/task_test.rb
      create      test/fixtures/tasks.yml
      invoke  resource_route
       route    resources :tasks
      invoke  responders_controller
      create    app/controllers/tasks_controller.rb
(erb):42:in `template': undefined method `update_attributes' for #<Rails::Generators::ActiveModel:0x0000000402aa40 @name="task"> (NoMethodError)
    from /home/candidosg/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/erb.rb:849:in `eval'
    from /home/candidosg/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/erb.rb:849:in `result'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/file_manipulation.rb:116:in `block in template'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:53:in `call'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:53:in `render'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:62:in `block (2 levels) in invoke!'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:62:in `open'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:62:in `block in invoke!'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:116:in `call'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb:116:in `invoke_with_conflict_check'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:60:in `invoke!'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions.rb:94:in `action'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/create_file.rb:25:in `create_file'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/actions/file_manipulation.rb:115:in `template'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/generators/named_base.rb:26:in `block in template'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/generators/named_base.rb:60:in `inside_template'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/generators/named_base.rb:25:in `template'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb:16:in `create_controller_files'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:115:in `invoke'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/group.rb:277:in `block in _invoke_for_class_method'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/shell.rb:68:in `with_padding'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/group.rb:266:in `_invoke_for_class_method'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/group.rb:133:in `_invoke_from_option_scaffold_controller'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/command.rb:27:in `run'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:126:in `invoke_command'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `block in invoke_all'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `each'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `map'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/invocation.rb:133:in `invoke_all'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/group.rb:232:in `dispatch'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.19.1/lib/thor/base.rb:440:in `start'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/generators.rb:157:in `invoke'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/commands/generate.rb:11:in `<top (required)>'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.1.2/lib/active_support/dependencies.rb:247:in `require'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.1.2/lib/active_support/dependencies.rb:247:in `block in require'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.1.2/lib/active_support/dependencies.rb:232:in `load_dependency'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/activesupport-4.1.2/lib/active_support/dependencies.rb:247:in `require'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/commands/commands_tasks.rb:135:in `generate_or_destroy'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/commands/commands_tasks.rb:51:in `generate'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
    from /home/candidosg/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.2/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:8:in `require'
    from bin/rails:8:in `<main>'

Flash message not set on destroy failure

This issue has come up before, but none of the solutions seem to work for me.

When I destroy a resource, I need to get redirected back to the index action ( on success and on fail ) so I use the location option.

   respond_with(@resource, location: resources_url)

On success, the notice flash message is set correctly.

When the destroy failed, it redirects to the index action and shows the notice flash message.
So as stated in other tickets, I added a base error on the resource through a before_destroy callback

This time I get redirected to the index action, but no flash message has been set.
Any advice?

updatin responders ERROR

Hi,

When I make a gem update in a cmd console I get this, do you have an idea what's happening ?

C:>gem update
Updating installed gems
Updating responders
ERROR: While executing gem ... (Gem::DependencyError)
Unresolved dependency found during sorting - activesupport (>= 0) (requested
by rails-dom-testing-1.0.2)

Thank you.

Custom Controller Action flashes not happening

I am trying to DRY up my custom controller actions' flash alerts/notices. What am I doing wrong here?

routes.rb:

resources :blogs do
  member do
    get :publish
  end
end

controller:

class BlogsController < ApplicationController
  respond_to :html
  responders :flash

  # ...CRUD

  def publish
    @model.publish! # simply calls update_attributes(...)
    respond_with @model
  end
end

responders.en.yml:

en:
  flash:
    actions:
      create:
        notice: '%{resource_name} was successfully created.'
        alert: '%{resource_name} could not be created.'
      update:
        notice: '%{resource_name} was successfully updated.'
        alert: '%{resource_name} could not be updated.'
      destroy:
        notice: '%{resource_name} was successfully removed.'
        alert: '%{resource_name} could not be removed.'
    blogs:
      publish:
        notice: '%{resource_name} was successfully published.'
        alert: '%{resource_name} could not be published.'

Thanks for your time.

update error because of being required railties (< 5, >= 4.2.0.alpha)

Hey guys,

While I was trying to run gem update, I got error below:

Updating responders
ERROR:  While executing gem ... (Gem::UnsatisfiableDependencyError)
    Unable to resolve dependency: 'responders (= 2.0.0)' requires 'railties (< 5, >= 4.2.0.alpha)'

In Rubygems, there is not related version of neither railties nor rails. Even I run gem install rails --pre, it returns that 4.1.4 is installed, not 4.2.x. Because of the halted process, I'm unable to update gems locally installled before ya.

Rails 3.2.2 flash responder not getting called

When upgrading to rails 3.2.2 from 3.2.1 some of my flash messages stopped working. If I have a regular respond with then it works fine. So this works fine

def my_action
  respond_with current_user
end

But if I give respond_with a block then it no longer displays the flash messages. This used to work but no longer works:

def my_action
  respond_with current_user do |format|
    format.html { redirect_to root_url }
  end
end

Responders uninitialized constant

Dears,

i got the below when running Responders master with rails3 master:

uninitialized constant ApplicationController::ApplicationResponder

Regards,
Shenouda Bertel

rails generate responders:install creates error

Hi

I'm using ruby-1.9.3-p194 & rails 3.2.6

Just created a new rails app and initialising reponders for the first time produced the following:

.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.6/lib/action_view/railtie.rb:42:in block (3 levels) in <class:Railtie>': undefined methoddebug_rjs=' for ActionView::Base:Class (NoMethodError)

Gemfile is very basic:

source 'http://rubygems.org'
gem 'rails', '> 3.2'
gem 'mysql2', '
> 0.3'
gem 'responders', '~> 0.9'

Would you pls let me know what to do about this. Thanks.

Regards
Ross

Devise & responders duplicate flash message after sign in

Hi,

I have a Rails 3.2.13 app with responders 0.9.3 and Devise 2.2.4. After a user signs in, I get two flash messages instead of one. I'm guessing this is due to this line on Devise SessionController and to the fact that I'm using self.responder = ApplicationResponder in the ApplicationController.

Here is how the flash messages look:

screen shot 2013-06-26 at 2 32 48 pm

one is a notice (Session creation) and the other is a success message (Administrator creation) (I configured responders to use config.responders.flash_keys = [ :success, :failure]).

Is there any way to disable the responders for Devise?

I thought seeing the code for the responders :resp1, :resp2 could help, but noticed there is no way to choose no responders for a controller (disabling them with something like :none).

Thanks.

Add "respond_to" to generator

After installing this gem and generating a scaffold, I get this error:

RuntimeError (In order to use respond_with, first you need to declare the formats your controller
responds to in the class level)

I suggest adding the line "respond_to :html, :xml" (since those are the formats commented out before each action) at the beginning of the class.

I'm using Rails 3 beta 4 and responders 0.6.1.

Thanks.

FlashResponder does not set flash messages on destroy failure

All the other flash messages work... except this one. Can't get this to work no matter what.

I've written a simple before_destroy callback for my model that both adds an error message to base, and returns false. My controller destroy method simply calls destroy and responds with the object.

I believe this is caused by this commit - 3bf2162

Deletion always redirects, and @flash_now will be true unless specified otherwise, so the flash message will not be shown.

Flash messages for js format

Hi!
I might be way off here so please be gentle... :)

In my application, I am returning flash messages embedded in a chunk of javascript code containing the result of a destroy method. This was working fine with a previous version of inherited_resources but now with the new responders, it is no longer working unless I add a to_js method to FlashResponder. That method is pretty much identical (no call to super) to the to_html method.

Is this how it is supposed to work?

Cheers,
Anders

config

I'm not too sure I understand rails' booting very well at all.

I expected the following initializer to work:

Rails.application.config.responders.namespace_lookup = true

It doesn't seem to. Couldn't responders rely on Rails.application.config.responders instead of copying in an initializer, or else use an after_initialize and use namespace_lookup = config... if namespace_lookup.nil?, say?

Not adding espond_to :html, :xml to controller.

When I run the scaffold generator it does not add the line:

respond_to :html, :xml

At the top of the controller. The first time you access the controller it throws an error that this line is missing.

Advise use of app/responders folder

In the docs it says you should use /lib/responders but that didn't work for me, so instead I'm using /app/responders/my_responder.rb which auto loads automatically in Rails 3.2.3 (unsure about earlier versions).

Feature request: flag to remove comments from controller

I always delete those comments and it seems like a waste to fork/clone responders just to add some touchups like that. Would you consider a patch that allows removing the comments? (or even easier, any chance you're cool with just removing the comments? The main rails scaffolds are for learning, but if someone's using responders I assume they know what the actions are doing. Thoughts?

0.9 on rubygems but not in repo

Guys, what am I missing here? I have just got responders 0.9 through bundle update and can't see the code inside the gem in this repo

undefined method `responders'

Using responders with rails master throws this error:

DEPRECATION WARNING: railtie_name is deprecated and has no effect. (called from /home/jo/.bundle/ruby/1.8/bundler/gems/responders-495f90108d58e69c4086fd128971e4a289731256-master/lib/responders.rb:11)
/home/jo/.bundle/ruby/1.8/bundler/gems/rails-16a5e918a06649ffac24fd5873b875daf66212ad-master/railties/lib/rails/railtie/configuration.rb:59:in `method_missing': undefined method `responders' for #<Rails::Railtie::Configuration:0x9eb7248> (NoMethodError)
    from /home/jo/.bundle/ruby/1.8/bundler/gems/responders-495f90108d58e69c4086fd128971e4a289731256-master/lib/responders.rb:20

Quiet the same result with inherited_resources.

Greetings
Johannes

CollectionResponder with Engines: undefined_method `my_engine_my_models_url'

When using the CollectionResponder inside an Rails Engine, the responder generates in illegal named route. It should not have the engine name as prefix. I found that in lib/responders/collection_responder.rb:

resources[0...-1] << klass.model_name.route_key.to_sym

fixes it (using the route_key method instead of plural). This does not break the existing test, but I don't know if there are any side effects. I did not manage to write a new test, but I am happy to contribute if this is the way to go.

updated_at is nil

Hi there,

In http_cache_responder.rb a resource might have a nil updated_at if it is a new record.

Maybe change line 20 to:

(resource.updated_at || Time.now).utc if resource.respond_to?(:updated_at)

Thanks - John

PS: I tried to create a test for this, but I didn't understand the setup of the test helper, particularly:
require File.expand_path(File.dirname(__FILE__) + "/../../rails/vendor/gems/environment")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.