Ruby implementation of the command line view function source code _ruby special Topics

Source: Internet
Author: User
Tags instance method

If you want to see the source code for the ActiveRecord update_attribute function, a more common approach is to search for Def Update_attribute directly from the Rails source. Blog The Pragmatic Studio introduces a more convenient technique to enable direct access to the editor in the Ruby command line.

The object of the Update_attribute method can be obtained by the Object#method method, while Method#source_location returns the file and location of the method definition. With this information, you can start the editor to view the source code:

Copy Code code as follows:

> method = User.first.method (: update_attribute)
User Load (0.5ms) SELECT ' users '. * from ' users ' LIMIT 1
=> #<method:user (ActiveRecord::P ersistence) #update_attribute >

> location = method.source_location
=> ["/users/wyx/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.2.11/lib/active_record/persistence.rb",
177]

> ' Subl #{location[0]}:#{location[1]} '
=> ""

Encapsulate this code as a function, add it to the. Pryrc or. IRBRC:

Copy Code code as follows:

Def source_for (object, method)
Location = Object.Method (method). source_location
' Subl #{location[0]}:#{location[1]} ' if location && location[0]!= ' (eval) '
Location
End

If you want to view the instance method Update_attribute for User, you can call it directly in PRY/IRB

Copy Code code as follows:

Source_for (User.first,: Update_attribute)

If you want to use another editor, replace the Subl #{location[0]}:#{location[1]} with the corresponding command line for this editor:

Copy Code code as follows:

# TextMate
Mate #{location[0]}-l #{location[1]}

# Macvim
Mvim #{location[0]} +#{location[1]}

# Emacs
Emacs {Location[0]} +#{location[1]}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.