Alias_Method and Class_Methods Don't Mix

alias_method and class_methods don't mix?

The calls to alias_method will attempt to operate on instance methods. There is no instance method named get in your Cache module, so it fails.

Because you want to alias class methods (methods on the metaclass of Cache), you would have to do something like:

class << Cache  # Change context to metaclass of Cache
alias_method :get_not_modified, :get
alias_method :get, :get_modified
end

Cache.get

class << Cache # Change context to metaclass of Cache
alias_method :get, :get_not_modified
end

Is there an alias_method for a class method?

alias_method aliases an instances method of the receiver. Class methods are actually instance methods defined on the singleton class of a class.

class MyClass
def self.a
"Hello World!"
end
end

method_1 = MyClass.method(:a).unbind
method_2 = MyClass.singleton_class.instance_method(:a)

method_1 == method_2
#=> true

To alias an instance method defined on the singleton class you can either open it up using the class << object syntax.

class << MyClass
alias_method :b, :a
end

MyClass.b
#=> "Hello World!"

Or you can refer to it directly using the singleton_class method.

MyClass.singleton_class.alias_method :c, :a

MyClass.c
#=> "Hello World!"

If you are still within the class context self will refer to the class. So the above could also be written as:

class MyClass
class << self
def a
"Hello World!"
end
alias_method :b, :a
end
end

Or

class MyClass
def self.a
"Hello World!"
end
singleton_class.alias_method :c, :a
end

Or a combination of the two.

ActiveSupport::Concern and alias_method_chain

It's old question, but I found an answer and I write for someone.

module LogStartEngine
extend ActiveSupport::Concern

define_method :start_engine_with_logging do
Rails.logger.info("Starting engine!")
start_engine_without_logging
Rails.logger.info("Engine started!")
end

included do
alias_method_chain :start_engine, :logging
end
end

define_method is point of this approach, it defines method dynamically on included (before alias_method_chain)

How to create custom helper functions in Laravel

Create a helpers.php file in your app folder and load it up with composer:

"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php" // <---- ADD THIS
]
},

After adding that to your composer.json file, run the following command:

composer dump-autoload

If you don't like keeping your helpers.php file in your app directory (because it's not a PSR-4 namespaced class file), you can do what the laravel.com website does: store the helpers.php in the bootstrap directory. Remember to set it in your composer.json file:

"files": [
"bootstrap/helpers.php"
]


Related Topics



Leave a reply



Submit