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.
Related
I am using ruby on rails 5.0.
It is common practice to use partials to share code fragments for views (e.g., in order to avoid duplication). Partials are files that start with an underscore, e.g., "_fields.html.erb".
After a certain time the directories are full of partials, and it can become quite hard to keep an overview which view calls which partials and which partial calls another partial et cetera.
Question: Is there an "easy" way or a tool or a gem that can help to give an overview of the call tree or the call dependencies? Perhaps by rendering an html page, generating a png or something similar.
Thank your for your thoughts!
This is an older gem that does that. It lets you view a tree-ish list of your partials.
https://github.com/skwp/PartialMap
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.
I'm looking to code a rails app that will only display an index page. It will not use any database access. All functionality will be implemented using one controller and javascript. What's the minimum number of files and directory structure needed for an app like this?
If that is all you want, why Rails?
Rails is a very complex framework that gives you a bunch of functionality at your fingertips. But if you specifically say you won't be using any of it (only one controller, so no routes to worry about, no database, so no models either, only one page, so layouts are meaningless...), why not just write a Sinatra app?
With Sinatra, you can write everything in one Ruby file. If you really want to, you can even pack all the templates in it, but that's overdoing it a bit. Thus, I'd say, 1 .rb, 1 or more templates (if you use partials), 1 .js and 1 .css.
I'm just starting out in Rails and there's a lot I still need to learn so I'm likely to be on Stackoverflow more often than normal asking beginner Rails / Ruby questions.
I'm just trying to figure out how Helpers work in Rails. From what I've seen so far, Helpers are intended to be used with Views and not so much with your Controllers.
However I would like to make a simple function that will validate the user input given in params (check if certain params are defined and optionally check if their value is valid).
Can anyone explain to me what would be the best way of implementing this? (Keeping in mind that I will want to use this in many different controllers so it should be globally available.)
I also noticed that by default Rails does not generate a lib folder in the main application folder. Are developers to place their libs outside the app folder in the main folder, or does Rails use libraries differently?
With regards to your validation issue, it depends on what you are validating.
If the data makes up objects from your problem domain, also known as models, then you should use the built in validators from ActiveModel. This is probably what you should do, but its hard to say without knowing the exact problem. See the Rails Guides on Validations. You can tell if this is the case by asking yourself if the data that needs validation will be stored after you get it. If so, its most definitely a model. An example of this kind of data would be the title and text fields of a blog post being sent to Rails from a browser form.
If the data is something tertiary to your models, or specific to presentation, then you should be fine using helpers. You noticed that helpers are used mostly in the views, and although this is true, theres nothing stopping you from using them in the controllers, you just have to declare that you will use them using the ActiveController#helper method. Inside the ApplicationController class, a lot of devs will put helper :all to just include all the helpers in all the controllers. Once the code has been required once, it doesn't really incur that big a performance hit.
Do note that almost all incoming data can be modeled using a model. A big school of thought in the Rails world subscribes to the Fat Model idea. People say that putting as much code as possible in the model and as little in the controller as possible separates concerns properly and leads to more maintainable code. This suggests that even if you don't think the incoming data is modelable (in the sense that you can create a model to represent it), you should try to make it a model and encapsulate the logic around validating it. However, you may find that making a helper function is faster, and either will work.
Your notion of validating user input is a good one. I get the feeling that as you are new to Rails you are used to doing these things yourself, but that doesn't quite apply here. In the Rails world, a lot of the common stuff like validations is handled by the framework. You don't have to check for presence in the params array, instead you call validates_presence_of on the model and let Rails spit the error out to the user. It makes things easier in the long run if you let the framework do what it is designed to.
With regards to your question about the lib folder, it doesn't really matter. You can put miscellaneous support files and libraries in the lib folder in the root directory and they will be available for use in your application (the files in the app folder). You can also choose to abstract your code into a plugin or a gem and include it that way, which a lot of people opt to do. My suggestion for this would be to read up on the notion of gems and plugins before diving in.
Want you want is probably a custom validator (in Rails3):
http://railscasts.com/episodes/211-validations-in-rails-3
You can either add libs in a lib folder you create, or add them to config/initializers in a file you add. Files in the initializers directory are automatically loaded by Rails.
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...