"Printf" testing in Rails - ruby-on-rails

I'm new to Rails and I'm aware it has things such as unit-testing built in. But I'm interested in doing some more simple tests that are equivalent to your "printf" in C. So I'm testing a login page I've written and want to trace the code to see what each line like my find methods are returning. I try outputting with "puts" but I don't get anything in the command-line.

I use puts statements all the time as well as the ruby debugger! It's great.
In rails you can do a couple things. I put "puts" in my code and when I run script/server at the command line, the output appears in my Terminal.app. I am running a Mac, but I am sure that there is a similar way to trace the activity of your app on your platform of choice.
The other option is to use the logger statement. you can call
logger.debug("My #{variable}")
and find these statements right in your log/development.log file.
Also, if you are running on a *nix system, you can use the "tail" command to trace the last statement written to your log one at a time.
tail -f log/development.log
This way you could write your statements and see them as they are happening. There are several levels of logging:
logger.warn
logger.info
logger.debug
logger.fatal
each environment (development, testing, production) will determine what "level" of logging will be called, so you may write log statements willy nilly with logger.debug while in development, but those log statements won't be written when you deploy based on the default log levels.

User something like this:
logger.info "method called with #{params.inspect}"
(you can put any variable inside the #{})
Once you're having fun with that, check out ./script/console and ruby-debug

Are you familiar with ruby-debug?
Install the ruby-debug gem.
Start your server with the -u option.
script/server -u
Put a debugger statement in your code where you want to stop.
You will have console access to your variables as well as the ability to step through your code.
Check the ruby-debug documentation for more details.

I've done this before - with Passenger, you don't have script/server's output, so I wrote this:
# extras/sexy_logging.rb
module SexyLogging
def log(text)
return true if RAILS_ENV == 'production'
string = "\e[0;32mLog:\e[m #{text}"
(100 - string.length).times do
string << ' '
end
string << "(#{caller.first})"
logger.debug string
end
end
ActiveRecord::Base.send :include, SexyLogging
ActionController::Base.send :include, SexyLogging
Then you can write
log variable
or
log 'Testing user'
tail -f log/development.log |grep Log:
and only see what you're logging, line by line and with colours.

Related

Can I detect if a rake task was triggered on the command line (as opposed to with cron, etc.)?

Of course it is unusual for rake tasks to be triggered by a controller (and kind of kludgey) but very common for them to be triggered by cron. I would like to detect from within a rake task whether it was started manually on the command line, or not.
How can I do that? This is a pretty standard thing to do in a shell script, but I'm unable to find any documentation about how to do it with a rake task.
Why the hate? People are downgrading this simply because they don't know the answer? 🤦🏼‍♂️
Here's a stab I took.
I tested this in both CL and Rails Console. I also tacked an invocation at the end of Application.rb to double check. But I haven't tested it in all the many other ways one might, so people should use this only with caution.
Likewise, I'm not certain that index 7 will be universal.
But I'm pretty sure it's accomplishable if you really want it.
task who_called: :environment do
puts case caller_locations[7].label
when "<main>" then :rails
when "invoke_task" then :cli
else
raise "unknown caller: #{location}"
end
end
Another suggestion is to always invoke the task with an ENV variable or an argument. You can assume that nil defaults to the command line, so people don't have to type unnecessary arguments.
Try this:
if defined?(Rails::Console)
....
end
Or you can check what caller[0] returns when you call from the cmd and use that in the if instead.

How to run code automatically when launching a Rails console?

Let's say I wanted a greeting every time the Rails console comes up:
Scotts-MBP-4:ucode scott$ rails c
Loading development environment (Rails 4.2.1)
Hello there! I'm a custom greeting
2.1.5 :001 >
Where would I put the puts 'Hello there! I\'m a custom greeting' statement?
Another Stackoverflow answer suggested, and I've read this elsewhere too, that I can put that in an initializer like this:
# config/initializers/console_greeting.rb
if defined?(Rails::Console)
puts 'Hello there! I\'m a custom greeting'
end
That doesn't work for me though :(. Even without the if defined?(Rails::Console) I still don't get output. Seems like initializers are not run when I enter a console, despite what others suggest.
I use ~/.irbrc for similar purposes (I require a gem in each console session). For example, my .irbrc
if (defined? Rails)
# Rails specific
end
# common for all irb sessions
You could use your project name to limit executing code to only one project's console:
if (defined? Rails) && (defined? YourProject)
# code goes here
end
The following will work in Rails 6:
Just pass a block to Rails.application.console, e.g
# config/initializers/custom_console_message.rb
if Rails.env.production?
Rails.application.console do
puts "Custom message here"
end
end
Now when starting the rails production console, the custom message will be printed. This code will not be executed when you start rails server.
Remove the if Rails.env.production? if you want this to run in all environments.

How to debug using rails console and puts in application

I want to get some lines printed in irb opened through rails console. I have seen a lot of SO questions of how to achieve it. But I get nothing in the irb.
below is the code--
def show
puts 'in show method'
#post = Feed.find_by_id params[:id]
puts #post.inspect
redirect_to root_path unless #post.present?
end
now I have opened server by command rails server. Also, In another terminal I gave the command rails console, it opened the irb prompt. when in browser I run localhost:3000/posts/82 it gives the correct post, but nothing is shown in the console. What step am I missing? I want to print something in the console when a particular method is called.
Best way to debug is to use the debugger command.
If you are using ruby 2.0 or above, you have to use the gem 'byebug' and if you are using 1.9 or below, then gem ruby-debug
then, when you run your server in development mode, your server will stop when it reaches the debugger allowing you to see your objects' state and modify them (much better than simply using puts
The program will stop in the same window that your server runs.
Some basic commands:
c continues the execution until next debugger is found
n runs the next command. If it is a function executes the
function
s step into the next command. If it is a
function, you will get into the function and see the variables
display expression on every step display the result of the
expression you write (very useful when debugging loops)
undisplay expression_number stops displaying the expresion
display shows all the expressions being displayed
list Displays the source code being executed
help shows the available commands help
command_name shows detailed info about a command
More info about debugging: http://guides.rubyonrails.org/debugging_rails_applications.html
The puts 'in show method' in line 2 won't show the output in rails console. Instead it shows the output in the same terminal where you did rails server. They might be lost with so much of output, so try to find it there itself.
Use Rails.logger.debug "in show method" etc.
In the second tab in terminal tail log/development.log like this
$ cd rails_app_root
$ tail -f log/development.log
or
$ cd rails_app_root
$ less +F log/development.log
There you will find all the output from the console.
Try to use Rails.logger
Rails.logger.info "Some debugging info I want to see in my
development log.------#{#post.inspect}"
It will print #post value in log file.
I am a big fan of puts debugging. e.g;
def index
method = Kernel.instance_method(:method)
p method.bind(request).call(:headers).source_location
#users = User.all
end
The above snippet helps you find where the method is implemented:
Processing by UsersController#index as */*
["/Users/aaron/git/rails/actionpack/lib/action_dispatch/http/request.rb", 201]
You can find more cool puts debugging here.

Rails puts to console

In my Rails app, there are some cases where code is being outputted with the puts command (for debugging purposes). Is there anyway to follow this output in the rails console (with the rails c command)? Or is there any other way to debug/view logs in the rails console?
Thanks!
For debugging, use Rails.logger instead of puts. For example:
Rails.logger.info "Some debugging info"
This will be logged to a log file in rails_app_root/log directory. If you are running in development environment locally, it will be logged to rails_app/log/development.log file.
Now, to see the log as they come in you can use tail command, like this:
tail -f log/development.log
Hope it helps.
Rails.logger is the best solution,one more think i want to add,if you want separate log file you could use like this
def read(args)
unless args.blank?
cache_key= self.get_cache_key(args)
end
logger = Logger.new("#{Rails.root}/log/cache_read.log")
logger.error("cache read scope == #{cache_key.to_s}")
end
so cache_read.log file having only this method log only.

How do I use a custom log for my rake tasks in Ruby on Rails?

I have a rake task that calls functions like this:
namespace :blah do
task :hello_world => :environment do
logger.info("Hello World")
helloworld2
end
end
def helloworld2
logger.info("Hello Again, World")
end
I want the log output to a custom log, and I really don't want to have to pass a log reference every time I make a function call. I found this somewhere (can't find it again):
def logger
##logger ||= Logger.new("#{RAILS_HOME}/log/blah.log")
end
But this does not work for me and I am not sure what it even does because I grabbed the code a long time ago and haven't used it until now. I can't search for ## on google (tried +"##" rails) to see what it does. Any help on this issue would be great. I am hoping for a quick solution and not having to install a gem or plugin (unless there is a really really good reason to.
Thanks!
rake disables logging in production mode. make sure you're running in development mode if you want it to log
What do you mean by "does not work for me"? I just tried this same code and it worked - created a new log file and put some text in it.
##logger is a class variable, it's a language issue, not Rails' one. I believe there's no need in further explanations :)
You've probably mistaken typing "function helloworld2" :)
Advanced Rails Recipes Recipe 84 from #topfunky shows how to define a custom logger. He has some code in the environment config file (production would look like this): RAILS_ROOT/config/environments/production.rb:
config.logger = RAILS_DEFAULT_LOGGER = Logger.new(config.log_path)
I'd test that out instead of redefining the class variable as you have. He might have something on http://nubyonrails.com to check as well.

Resources