How to extend a controller method from a Rails Engine without having to duplicate the whole thing?
Trying to extend https://github.com/radar/forem/blob/rails4/app/controllers/forem/forums_controller.rb -- app/decorators/controllers/forem/forums_controller_decorator.rb
:
Forem::ForumsController.class_eval do
def show
# A simple `include` here or something?
# New code goes here...
end
end
Forem::ForumsController.class_eval do
def show
# Repeat ALL the code from:
# https://github.com/radar/forem/blob/rails4/app/controllers/forem/forums_controller.rb
authorize! :show, @forum
register_view
@topics = if forem_admin_or_moderator?(@forum)
@forum.topics
else
@forum.topics.visible.approved_or_pending_review_for(forem_user)
end
@topics = @topics.by_pinned_or_most_recent_post
# Kaminari allows to configure the method and param used
@topics = @topics.send(pagination_method, params[pagination_param]).per(Forem.per_page)
respond_to do |format|
format.html
format.atom { render :layout => false }
end
# New code goes here...
end
end
We use this gem for multiple applications and engines to do exactly what you want:
I could extend a controller method from a Rails Engine without having to duplicate code using alias_method
module ValueSets
SetsController.class_eval do
def new_with_authorize
new_without_authorize
authorize @value_set
end
alias_method :new_without_authorize, :new
alias_method :new, :new_with_authorize
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.