Ruby on Rails: testing if values do exist? - ruby-on-rails

I'm trying to test if my values are existing... Not sure how to do this, I'm just starting to learn Ruby on Rails. Hopefully someone can point me to the right direction?
Lets say I have this block of codes:
#lv = {'apple' => ['red', 'round'], 'iPhone' => ['device', 'phone']}
if params[:var]
#lv.each do |key, tags|
if params[:var] == key
lvtags = #lv[params[key]]
lvtags.each do |tag|
#tags = client.tag_recent_media(tag)
end
end
end
end
I'm trying to see if the loop through the if params[:var] == key works. I'd like to somehow output like an alert() type thing, to test if key has a value? Is there something like alert(key)? where it'll show if key has something? Or if I can test if lvtags has a value that its supposed to pop out?
For instance, if ?var=0
Then I'd like to test alert(lvtags), and thus this is supposed to pop out apple or something, some value associated to lvtags = #lv[params[key]]. How do we normally test something like this in rails?
Thanks

You can do a puts key. Puts converts its first param to string and outputs it in the stdout (your console).
It might be easier for you to use a debugger, though. You can open a console debugger (think gdb) with
require 'debugger'; debugger
Be sure to install the debugger gem first. Put the following in your Gemfile
gem 'debugger', group: [:development, :test]
Edit: added a link to the debugger gem's github page.

You can just log it in your console.
Rails.logger.info key.inspect # or whichever's value you want to check
It's also helpful when checking objects

Related

byebug: break on output to console

I have some code (a Rails app) that generates output to console.
I'd like to use byebug to get the location of whatever is generating that output.
Is there a way to do that?
Could you specify a little more? What do you mean by having "the location of whatever is generating that output"? Do you mean the trace? If yes, buybug has a backtrace (you can use where also) command. Have you look into this?
EDIT:
You could use pry with byebug (with the pry-byebug) and accomplish what you want.
Use pry gem for debugging code
Gemfile
gem 'pry'
add binding.pry anywhere to debug code

Quick way to see variables that apply in current scope and which object self refers to, RAILS

Is there a quick way to find out which variables apply with the current scope, and which object 'self' refers to in Ruby on Rails?
I think pry is a great solution, although debugger, as #jvnill suggested, also works.
gem install pry # or add to bundler
In your code you need to add the following wherever you are interested in inspecting the scope:
require 'pry'
binding.pry # this will open a console view with the binding as the current scope
In pry there is something built in for what you're asking:
pry> ls
ls will show variables and methods that can be called and from which objects/classes they originate.
pry> self # will return self in the current context
pry> pry-backtrace # shows the current stack
pry> help # will show the list of commands
pry> cd <some obj> # will change the scope to the target object
pry> exit # move back out to previous console scope
Clarify if you are looking for something entirely different.
Using the gem "pry", issue the command "ls -l" in the context of pry for a list of local variables (together with values in the variables).
I really like using the Better Errors gem, then I just "raise #somevar" where I need, that way I can use the in browser console and poke it with a stick. :) god I love that thing.

How do I output a variable in a rspec test?

Is there a quick way to output the value of variable in a rspec test? Something like this for example, in a controller to output a variable, I do:
raise variable.to_yaml
Is there something similar I can do in a rspec test to see the contents of a variable?
If you want the output to go into the log file (i.e. logs/test.log), you can use the rails logger.
Rails.logger.debug variable.inspect
Rails.logger.debug variable.to_yaml
If you want to see the output in the console, you can use the pretty printer 'pp'.
require 'pp'
it 'does something'
thing = Factory(:something)
pp thing
end
Or you can use good 'ol puts
puts thing.to_yaml
At this moment (Rails 4) you can log it:
p variable
Use this:
$stderr.puts variable.to_yaml
You can use the gem pry to do this
add gem "pry" in your gemfile
bundle install
Now you can any test any variable by putting "binding.pry" just after that variable. Run bundle exec rspec filepath and you will get something like rails c, then write directly your variable.
I hope it makes sense

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.

How to determine the value of a controller variable during execution in Ruby on Rails?

What is the best way for me to determine a controller variable's value during execution?
For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?
Yes. The easiest way is to raise the value as a string. Like so: raise #foo.to_s
Or, you can install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.
Inside the debugger prompt, you have many commands, including p to print the value of a variable.
Update: here's a bit more about ruby-debug.
If you have a controller instance variable named #foo, then in your controller you can simply do something like:
logger.debug "#foo is: #{#foo}"
Additionally, you can output the value in your view template using:
<%= debug #foo %>
I prefer using the inspect method like so:
raise #foo.inspect
It has more information than to_s, like the attribute values.
Summary from Jordi Bunster, John Topley, and Jaryl:
I. Quick and dirty way:
raise #foo.inspect
in your controller. Or
<% raise #foo.inspect %>
in your view.
II. Proper logging to you development.log:
logger.debug "#foo == #{#foo.inspect}"
III. Full-fledged debugging:
Install the debugger (gem install ruby-debug), and then start the development server with the --debugger flag. Then, in your code, call the debugger instruction.
Inside the debugger prompt, you have many commands, including p to print the value of a variable.
Raising an exception is the fastest way if you just need to look at a value, but it's worth the time to learn how to use the debugger properly. It's rare that you would only need to just see the value of a variable, you are likely trying to find a bug in your code, and that's what a debugger is for.
Sending the info to the development log is slower than either of the other two options here so far if you learn how to use the debugger (who wants to read through log files). Use the logger for production, you are going to want to see what the value was when somebody calls you up and says everything is broken.
Well, I usually prefer the standard error output
$stderr.print("whatever")
Its simple and does the job.
Add pry-moves to Gemfile: gem 'pry-moves'
Insert binding.pry where you want to stop
Type variable's name to see its value
Then continue by typing c, move to next line with n or perform other debugging actions until you will resolve the issue.

Resources