Hello.
I think that the most required technology for development is debugging ability. Especially for me who is good at mass-producing bugs, debugging ability is very important.
Therefore, I would like to put together the debugging code that I usually use in development.
I will write a list of code that can be used in Ruby on Rails and may be useful for debugging. There is also code that can be used in Ruby.
It is supposed to be used when starting byebug or with rails console
. If you are not sure how to use byebug, please use it in the following article.
https://web-nari.net/2018/03/16/byebug/
Returns a list of methods that can be referenced by the variable hoge
and whose method name contains method_name
.
hoge.methods.select {|name| name.to_s.include?("method_name") }
Returns the class in which the foo
method that can be referenced by the variable hoge
is defined.
hoge.method(:foo)
Returns the path of the file in which the foo
method that can be referenced by the variable hoge
is defined.
hoge.method(:foo).source_location
Returns a list of save callbacks defined in the class Hoge
. If after or before is given to the argument of cb.kind.eql?
, the callbacks defined in the after_callback function and the before_callback function are returned, respectively.
Hoge._save_callbacks.select { |cb| cb.kind.eql?(:after) }.map { |cb| cb.filter }
In addition to save
, the following callback functions can be used respectively.
=> [:validate,
:validation,
:initialize,
:find,
:touch,
:save,
:create,
:update,
:destroy,
:commit,
:rollback,
:before_commit,
:before_commit_without_transaction_enrollment,
:commit_without_transaction_enrollment,
:rollback_without_transaction_enrollment]
For example, if you want to know the list of after_validation
callbacks, do as follows.
Hoge._validation_callbacks.select { |cb| cb.kind.eql?(:after) }.map { |cb| cb.filter }
Converts the name : string
to the appropriate class. In the case of the example, String
is returned. A NameError: uninitialized constant
is raised if there is no such class.
:string.to_s.classify.constantize
Check the class of the object named hoge
.
hoge.class
You can also search for inherited classes of the object hoge
and their ancestors.
hoge.superclass #Find parent class
hoge.ancestors #Search for ancestors
Returns the instance variable that the object named hoge
has. Class variables can be referenced with class_variables
.
hoge.instance_variables
When I wrote it for the momentum of the title, it was very few.
We will continue to add more.
Recommended Posts