【发布时间】:2020-05-19 01:11:46
【问题描述】:
我有一个 AccountController 类,这个控制器类在应用程序内核中。我不想对内核进行更改,因此我要去猴子补丁它。 Controller 有一个名为 successful_authentication 的方法,我已经对其进行了重写。在新方法中(在我的模块中),此代码调用名为 load_favourite_or_index 的新方法。
我了解到 alias_method_chain 现在已弃用,不应使用。我正在尝试在 AccountController 之前预先添加我的模块。但是什么也没发生,我猜我的前置代码不正确,请你帮帮我?这是我的代码。
# frozen_string_literal: true
module RedmineKapDesign
module Patches
module AccountControllerPatch
def self.prepended(base) # :nodoc:
class << base
prepend InstanceMethods
end
end
module InstanceMethods
def successful_authentication(user)
logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
# Valid user
self.logged_user = user
logger.info "Setting.autologin? = #{Setting.autologin?}, params[:autologin] = #{params[:autologin]}"
# generate a key and set cookie if autologin
if params[:autologin] && Setting.autologin?
set_autologin_cookie(user)
end
call_hook(:controller_account_success_authentication_after, {:user => user})
load_favourite_page_or_index
#redirect_back_or_default my_page_path
end
def load_favourite_page_or_index
user = User.current
favourite_page_field = CustomField.where(name: ["Favourite page", "favourite page", "favorite page", "Favourite page", "Любимая страница", "любимая страница", "Избранная страница", "избранная страница"]).first
page_url = user.custom_values.where(custom_field_id: favourite_page_field.id).first.value
if page_url.empty?
redirect_back_or_default my_page_path
else
redirect_to(page_url)
end
end
def self.hello
puts "Hello"
end
end
end
end
end
#unless AccountController.included_modules.include?(RedmineKapDesign::Patches::AccountControllerPatch)
# AccountController.send(:prepend, RedmineKapDesign::Patches::AccountControllerPatch)
#end
AccountController.singleton_class.prepend(RedmineKapDesign::Patches::AccountControllerPatch)
【问题讨论】:
标签: ruby-on-rails ruby metaprogramming monkeypatching