【问题标题】:How to correctly prepend module in a class?如何在课程中正确添加模块?
【发布时间】: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


    【解决方案1】:

    您不需要将实例方法分离到单独的模块中。您可以将它们放在 AccountControllerPatch 中,并在您正在猴子修补的任何类前面加上它。

    module RedmineKapDesign
      module Patches
        module AccountControllerPatch
          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
    

    只有在使用模块混合模式时,类方法才真正需要使用单独的模块。在框架代码中使用单独的 InstanceMethods 模块可用于组织目的。但是在一个简单的猴子补丁中,它只会变得更加混乱。

    # config/initializers/my_monkey_patch.rb
    # You should explicity require classes in initializers 
    require Rails.root.join('path', 'to', 'monkeypatch')
    require Rails.root.join('path', 'to', 'target')
    
    ::AccountController.prepend RedmineKapDesign::Patches::AccountControllerPatch
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2019-05-23
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2016-01-26
      • 2018-10-15
      • 2020-10-14
      • 2014-06-08
      相关资源
      最近更新 更多