print and debugging functions in rails? - ruby-on-rails

In php one can print_r() anywhere in the view, controller, or model. Is there anything like that in rails? I tried to_yaml and inspect. They don't seem to print things out from the model. Is it only allowed to be used in view? If not any example in model or controller?

This doesn't really exist because it's the lest effective way of debugging.
Being able to dump output to the browser depends on where you are. It's trivially easy in views, slightly cumbersome in controllers, and too difficult to be worth-while from models.
Fortunately, there are much better tools than simply dumping things into the browser.
You can use pry to stop mid-request, open a REPL environment and interactively query or modify the state of your running application.
If you simply want to trace the flow of execution through output, use the logger:
Rails.logger.info(my_object.inspect)

Normally you'll identify problems in your model, controller or integration tests long before it becomes an issue. In that context you can use puts to output whatever you want when instrumenting bits of code and it will show up in your test output:
puts object.inspect
Within the Rails operational environment you can use Rails.logger:
Rails.logger.debug(object.inspect)
This will show up in log/development.org where you can see what's going on. It's best to leave this at debug level so it doesn't clutter up your production logs if left in by accident.

Short answer is, you can't. At least not in one line. And not only because this is a violation of MVC, there are also practical reasons that prevent this.
There is no reliable way to output a bunch of data in an arbitrary format and keep it valid. Outputting it in JSON views may easily result in invalid data. So if your debug data can only be handled by a browser, that output should only be specified in views for browsers. Even if none other exist, separate concerns.
There is a substitute, of course. Rails 4.2.0 ships an app template with web_console. All you need to start using it is add a call to console in your views somewhere, like the app's general layout file. If that's actually ERB, add this line below:
<%= console %>
And wherever it appears, you have a REPL in the context of the currently rendered view, where you can easily inspect objects and even perform actions that change your data.
There is also a variety of methods to output data into the server's console or log file. They've been listed in other answers. I'll add a little to the solution involving logger.
Rails Panel. It's a Chrome extension that adds another tab to Chrome Dev Tools (that show up behind F12) named "Rails". For it to work, you need to add a meta_request gem to your app (make sure it's in group development!). Once working, it will show loads of data about how the page was processed:
Time spent fetching data, rendering it
Parameters for the given request
Executed DB queries, duration and lines they've been triggered by
View files involved
Log entries emitted on this request and what triggered that
Errors encountered
This one and some other debugging things are discussed in this Railscast.

Related

Restrictions on user-submitted code

I have a Ruby on Rails application, and one of its functions is to present JSON data to the user in table form. Before this step, I intend to add a way for users to tweak the JSON data by means of uploading their own Ruby code files that handle this.
This has its dangers. I definitely don't want any form of access (reading or writing) to the databases, nor do I want it to be able to call anything in another file. How can I limit the file in this way?
Essentially all I need is for the main code to call the function in the user-submitted file with the JSON as the parameter, and returning JSON back. All logic during this manipulation of the JSON must happen in and only in the user file.
I've looked around for ways to do this with no luck. I've seen this question:
Restricting access to user submitted code in Rails
The issue here is that I'd prefer an approach that doesn't require a gem. Also sandboxing seems rather complicated for the approach I want, which is a blanket restriction, and not specific things.
I intend to raise the $SAFE level to 4 before calling the user-supplied code/method. That doesn't seem to prevent calling other methods in the application though.

Several PhantomJS calls in a RoR application

I have a RoR application that given a set of N URLs to parse, will perform N shell calls for a given PhantomJS (actually is a CasperJS) script.
So,
Right now I have something like this:
urls_to_parse = ['first.html', 'second.html',...]
urls_to_parse.each do |url|
parse_results = \`casperjs parse_urls.js '#{url}'\`
end
I have never done this before. Launching shell scripts from a RoR/Ruby application, so I am wondering if this is a good approach and what alternative may I have. So, why I use PhantomJS in combination with RoR?
I basically have an API (RoR app) that keeps receiving urls that need to be parsed. They need to be parsed in a headless browser manner. The page actually needs to be rendered (that's why I don't use Nokogiri or any other HTML parser).
I am concerned about putting this up to production performance wise, and before going forward I would like to know if I am doing this correctly, or I can do it in a better way.
It's possible I thought about doing the same thing, but even with a headless browser I would be really concerned about the speed and bandwidth your server is going to need to have. I use capser in conjuction with Python and it works very well for me. I read stdout spit back from firing the casper scripts, but I don't parse and scrape on the fly like you're talking about doing. I would imagine it's okay, but ideally you already have a cached database of results when people search. Maybe if it is a very very basic search you'll be okay, but I don't know.

Can I Use Multiple Preprocessors on Rails Views?

Using Rails 3.2, you can make files in the asset pipeline use multiple preprocessors by appending multiple file extensions, thusly: index.css.scss.erb
I tried doing this with a view (index.html.slim.erb) and it didn't seem to know what to do (more accurately, it just didn't find the view at all).
Does Rails really not pass views through Tilt? Is there another way I can make a view run through one preprocessor and then another?
(Context: I'm working on something that's intended to modify HTML fed in before being returned, so I'd want it to run after haml/slim/erb.)
Indeed, you can not. Rails does not use tilt for view templates.
One reason it would be complicated for it to do so, is that in normal operation ERB actually 'compiles' to ruby code, not to text, for performance. Ie, the erb template compiles once to live ruby code, which is then executed every time it needs to be displayed in a different context.
I don't know built in way to do what you want. You could certainly roll your own. Nobody says you have to call "render 'template'" to render. Don't forget you can always
render :text => any_method_that_returns_a_string
You could pass things through Tilt yourself. You may see some performance degredation compared to what Rails usually does.

Is there any way for a malicious user to view the controller/model code in my Rails app while it is running?

This is probably a stupid question but I'll go ahead and humble myself.
The Ruby code in my controllers and models are interpreted so that a HTML result is sent to the browser. Ok, I get that part.
But is there any way for a mailicious user to somehow take a peek at the Ruby code in the controllers and models by bypassing the process that converts or interprets that code before it is sent to the browser?
The reason I'm concerned is I am planning on doing some order processing in my app and if a malicious user was able to do that, they might be able to figure out how to do all kinds of unpleasant things.
Side tip: make sure you use html_escape or h to escape user data and prevent someone from injecting code into your site. For example, use
<%= h(person.name) %> so that someone can't put javascript in the name field and have it run when people view that page.
Nope. Try and navigate to the file yourself in the browser, you won't be able to see it. Your biggest worry should be someone trying to fake out GETs and POSTs because they know how REST works.
Assuming you have things set up correctly, then the web server in front of Rails is pointed to the /public directory. So anything in that directory may be open to direct attack. However, the web server intercepts the HTTP call based on certain criteria and redirects it to Rails for processing.
The architecture of Rails makes it impossible for model and controller code to be exposed to the public. There is a possibility that view code is viewable, but ONLY if you seriously mess up the code (I think). I have never managed to expose code to the client by accident, and I have never deliberately attempted to do so.

How can i 'insert' a small ruby app into Ruby on Rails to make a web page?

I have a small ruby application that I made on my local machine. It uses a text file insted of a database. It's a simple app that takes in a word, processes it against the text file, and then outputs the results using puts.
I would like to fit it into a RoR framework, hosted on my personal machine. I have run through some lessons and tutorials in a few books and online materials I have, but they all involve databases.
I read thru the notes in config/environment.rb and found at line 19 instructions to uncomment the line that removes ActiveRecord.
I am currently looking for the appropriate directories to put the text file itself, and the code from the ruby app that reads this text file. Thank you.
You probably want to do something like the following:
Have a controller that takes the word as a parameter.
Turn you app into a function that takes the word as a parameter and returns the results (instead of doing puts)
Call the function from your controller and render the results (e.g. something like:
render :text => my_func(word)
This sounds like a better fit for something more lightweight like Sinatra.
If you were bound and determined to use Rails, you could make a controller with an action that just runs the code from your program, but it seems like overkill. You wouldn't be using 99.9% of the framework's capabilities, so why is it even there?
If your just trying to give it a little interface you could look at Shoes which is an easy to use multi-platform gui framework.
Or like someone mentioned take a look at Sinatra.
You can simply use rails without worrying about ActiveRecord. I'd sugest making your little application into a class and requiring the file in a controller you want to use (or in environment.rb). Put the file in lib and if the data is temporary, "tmp" is fine or just put it in "lib" with the script you wrote even "db" is a fine location for it. To make a view just run your code and put the return in a class variable and make a view for it.
A model need not inherit from ActiveRecord::Base. Or anything else. As long as it follows the naming convention for models, Rails will pick it up without problem.
Having said that, if you're really looking at a one-model, one-controller, one-action, no-database app, then Sinatra would probably be a really good lightweight place to start...

Resources