问题
There is a private method in the spree-auth-devise gem. The method is inside the controller UserSessionsController https://github.com/spree/spree_auth_devise/blob/master/lib/controllers/frontend/spree/user_sessions_controller.rb
I wish to override the function "redirect_back_or_default".
Is this possible?
Update
After mixing and matching between your answers and doing some googling, I arrived at this solution:
Spree::UserSessionsController.class_eval do
private
def redirect_back_or_default(default)
if default == "/admin/orders" or session["spree_user_return_to"] == "/admin/orders"
redirect_to("/admin/users")
else
redirect_to(session["spree_user_return_to"] || default)
end
session["spree_user_return_to"] = nil
end
end
And I have placed the script file in config/initializers.
Thank you all.
回答1:
Of course you can override private methods:
class Super
private def i_am_private
'private method'
end
end
class Sub < Super
private def i_am_private
'overridden ' << super
end
end
Sub.new.send(:i_am_private)
# => 'overridden private method'
回答2:
You could do something like this:
class HelloWorld
def run
say_hello_world
end
private
def say_hello_world
puts "hello world"
end
end
HelloWorld.new.run
"hello world"
=> nil
Now let's extend/override the current behaviour.
class HelloWorld
private
def say_hello_world
puts "Goodbye"
end
end
HelloWorld.new.run
"Goodbye"
=> nil
So since this works and is possible, how about monkey patching it. Something like this:
class Spree::UserSessionsController < Devise::SessionsController
private
def redirect_back_or_default(default)
# your logic
end
end
来源:https://stackoverflow.com/questions/33592221/override-a-private-method-in-the-lib-folder-of-a-gem