Any way, in the console, to get info on what a certain method does?
Pry (an IRB alternative) supports documentation browsing:
$ pry
[1] pry(main)> require 'csv'
#=> true
[2] pry(main)> csv = CSV.new('')
#=> <#CSV io_type:StringIO encoding:UTF-8 lineno:0 col_sep:"," row_sep:"\n" quote_char:"\"">
[3] pry(main)> show-doc csv.first
From: enum.c (C Method):
Owner: Enumerable
Visibility: public
Signature: first(*arg1)
Number of lines: 8
Returns the first element, or the first n elements, of the enumerable.
If the enumerable is empty, the first form returns nil, and the
second form returns an empty array.
%w[foo bar baz].first #=> "foo"
%w[foo bar baz].first(2) #=> ["foo", "bar"]
%w[foo bar baz].first(10) #=> ["foo", "bar", "baz"]
[].first #=> nil
According to the docs, you don't have to generate the documentation beforehand:
The Pry documentation system does not rely on pre-generated
rdoc
or
ri
, instead it grabs the comments directly above the method on demand.
This results in speedier documentation retrieval and allows the Pry
system to retrieve documentation for methods that would not be picked
up byrdoc
.
How to find where a method is defined at runtime?
This is really late, but here's how you can find where a method is defined:
http://gist.github.com/76951
# How to find out where a method comes from.
# Learned this from Dave Thomas while teaching Advanced Ruby Studio
# Makes the case for separating method definitions into
# modules, especially when enhancing built-in classes.
module Perpetrator
def crime
end
end
class Fixnum
include Perpetrator
end
p 2.method(:crime) # The "2" here is an instance of Fixnum.
#<Method: Fixnum(Perpetrator)#crime>
If you're on Ruby 1.9+, you can use source_location
require 'csv'
p CSV.new('string').method(:flock)
# => #<Method: CSV#flock>
CSV.new('string').method(:flock).source_location
# => ["/path/to/ruby/1.9.2-p290/lib/ruby/1.9.1/forwardable.rb", 180]
Note that this won't work on everything, like native compiled code. The Method class has some neat functions, too, like Method#owner which returns the file where the method is defined.
EDIT: Also see the __file__
and __line__
and notes for REE in the other answer, they're handy too. -- wg
How to test a Rails Class function in the console?
Your function2
is an instance method. You need to call it on instance of Model
class like:
Model.new.function2(input_1,input_2)
Happy Coding!
How to test a rails method through the rails console
I'm assuming you're including StateMatchesZipCodeConcern
in your User
model.
That means the method validate_against_multi_state_zip_codes
will be a method on User
instances.
You're trying to call this method on the return of the User
's address
method, which is what throws NoMethodError
. In addition, you've made this method private
so you won't be able to call it anyway.
Put the method above the private
line in the module and call it like this: User.last.validate_against_multi_state_zip_codes?
Is there a way to view a method's source code from the Rails console?
You can also use pry (http://pry.github.com/) which is like IRB on steroids. You can do stuff like:
[1] pry(main)> show-source Array#each
From: array.c in Ruby Core (C Method):
Number of lines: 11
Owner: Array
Visibility: public
VALUE
rb_ary_each(VALUE ary)
{
long i;
RETURN_ENUMERATOR(ary, 0, 0);
for (i=0; i<RARRAY_LEN(ary); i++) {
rb_yield(RARRAY_PTR(ary)[i]);
}
return ary;
}
[2] pry(main)> show-doc Array#each
From: array.c in Ruby Core (C Method):
Number of lines: 11
Owner: Array
Visibility: public
Signature: each()
Calls block once for each element in self, passing that
element as a parameter.
If no block is given, an enumerator is returned instead.
a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
produces:
a -- b -- c --
Call a method and initiate debugging from the rails console without editing the source code?
mhm this sound a bit like metaprogramming for me, you may inject a debugging method at runtime in your model, which will add the debugging statement just before the method call so you can inspect the call as needed, like:
m = MyModel.last
m.class.send(:define_method, :debug_my_method){debugger; my_method}
m.debug_my_method
this should do on the irb (just tested it on may rails console)
When creating a method without a class in the Rails console, what class is the method under?
Ruby creates a object of Object class when you run your console, so all methods are private instance methods of Object class, you can run this to verify.
Object.private_instance_methods.include? :test
So when you define your methods in console It is interpreted to this
class Object
def test
puts "hi"
end
end
More explanation
I was wanted to explain this but a detailed article is written on this topic,
https://www.sitepoint.com/rubys-top-self-object/
In Ruby, how do I check if method foo=() is defined?
The problem is that the foo=
method is designed to be used in assignments. You can use defined?
in the following way to see what's going on:
defined?(self.foo=())
#=> nil
defined?(self.foo = "bar")
#=> nil
def foo=(bar)
end
defined?(self.foo=())
#=> "assignment"
defined?(self.foo = "bar")
#=> "assignment"
Compare that to:
def foo
end
defined?(foo)
#=> "method"
To test if the foo=
method is defined, you should use respond_to?
instead:
respond_to?(:foo=)
#=> false
def foo=(bar)
end
respond_to?(:foo=)
#=> true
Related Topics
Net::Ssh with Non Unix/Linux Host
Tilt (Kramdown) Preventing Erb Processing When Rendering Markdown
If Referer = "/Search", Do X, Else Do Y: "Bad Argument (Expected Uri Object or Uri String)"
Running Rake Task from Within War File
Knowing When Resque Worker Had Completed Job
How to Use Local or Instance Variable in Ruby Code in Coffeescript in Haml Template
Rails: Logging the Entire Stack Trace of an Exception
Ruby - How to Retrieve Sum in Array Group by Multiple Keys with Condition Max
Watir and Text Field Inside Iframe
How to Display Error Messages in a Multi-Model Form with Transaction
Multiple Limit Condition in Mongodb
Ruby Before_Validation Triggers Infinite Loop of Call Back
How to Make the Say Command Echo a Variable Value in a Script