Modifying Rails: How do advanced users find out what needs to be changed? - ruby-on-rails

I've been using Rails for a few months now, and I'm quite comfortable writing up a project & manipulating Rails to my needs, etc.
Recently I've been trying to get a little more advanced, so I've attempted to modify/add to the existing rails codebase: add new form helper methods, add a responds_to :pdf method, etc...and I've been having a lot of problems.
The difficulty is learning which code I need to modify; where that code is located, and how to ensure I don't miss related code in other files. I'm guessing there's a way people learn to do this, but at the moment I'm mostly just guessing-and-hoping.
I guess my question is, how do Rails folks go about learning where the code they need to modify is edited & the approach to editing it? It seems like it's just something you need to know from prior familiarity, but I'm guessing there has to be a simple method for understanding where (and what) to edit.
Any ideas appreciated...cheers

I highly recommend Jose Valim's Crafting Rails Applications
You go through advanced projects, building out the types of engines and customizations that will take you to the next level in your Rails development.
From the site:
This book will help you understand Rails 3’s inner workings, including
generators, template handlers, internationalization, routing, and
responders.

What you are asking for is how MVC works. Basicly you can say:
1.) Put logic to the model! The model is the pivot everything turns around.
2.) The Controller is a middleman between the model and the view. You dont put any logic here that isnt related to selecting data from the database that should be displayed in the view. If you use one selection logic more than once create a scope in the Model and use it in the Controller.
3.) The View is only there to display things! You dont put any logic here! All the logic comes from the model and the data comes from the controller. The only logic your using here are loops through arrays of data that should be displayed.
Then you have some things missing. If you have a task that is related to an external service like lets say a SOAP Service you write a class for that too! Just whithout using ActiveRecord::Base inheritance like its generated by the scaffolder. You can call this Class in other models. Dont put this to the controller or copy the code in every class that needs it! Stay DRY (Dont Repeat Yourself). Just write a class for it and include it in the other models!
Another thing thats a Database basic: Dont store data that could be calculated from other fields from the database! You can add methods that calculate the stuff you need but dont start with duplicates.

Related

What are the steps for modifying an existing rails application

I am new to ruby on rails and I am working on a web application written by ruby on rails. It has more than 10 models and I need to add some new attributes to some of the models as well as new methods and views. I also will need to remove or enhance some of the functionality. I know that I would need to generate new migrations and from there add/remove new columns. Then in controllers, add/modify methods, and update the views.
I wanted to know what would be the best steps (and in which order) for doing the above tasks. Also, do I need to change other files in folders like test or any other folder? What things should I consider to minimize the troubles later?
Thanks in Advance.
Since you are new to rails, the first thing you should do is to read through the getting started guide. This will help you understand the fundamentals of the rails framework and the application you inherited. After that, there are several other guides worth reading (from the same site) that may be directly applicable to the work you are doing.
Another incredibly helpful resource is railscasts. Some of these are outdated, but they are still a great starting place and can help introduce you to both new, powerful gems and rails techniques to get the work done faster and better.
As to your specific question, rails is built on an MVC architecture (meaning Model Views Controllers). It is in your best interest to try and follow this practice whenever possible. Reading up on this will clarify some of your questions as well.
When you run a migration, you will be modifying your database. The changes are viewable in the database schema (which should never be modified by hand, always modify it through migrations). This will add attributes to your models whose table you modified. In the controllers, you will add logic to deal with all of these things and the views will present the data to your users (or allow users to enter data). Asking which order is best is probably rather opinion based, but I would say you should modify the tables (run needed migrations) first. This way you can then generate the logic to deal with the new attributes. I would then create the controller logic and finally the views.
You also ask what other files need to be changed. This is heavily dependent on your system. At a base level, you should definitely be writing tests to support the logic you are generating (and many developers will advocate that you should do this before you write the other logic, a process called Test Driven Development).
TL;DR: Read the guides, work through a basic tutorial, and watch some Railscasts. This should get you up to speed on the process and best practices that go along with rails development.

Un-bloating models in rails 3.1

Just learning rails, developing first app and having trouble finding a straight answer to this question!
I want to keep my models as lean as possible and really only want to use them to represent objects that I might want to render in my views. Therefore, I want to remove some of the logic from one particular model and store it in a separate file. I have seen numerous guides (on this site and others) that suggest the following;
never "require" anything from inside a rails app
Store additional files in the lib folder - they used to be auto loaded in older rails releases but now you need to add an extra line in a config file to get this to happen (Example.
So I added the line, stuck the file in the lib folder, and it all worked fine. So on to the question;
I can't shake the feeling that the fact that I had to go and put some bespoke code into the config file means I'm doing this wrong (given convention over configuration). Why are people having to faff around editing configuration files to get rails to do something so basic?
Is that the best way or are there additional considerations that I'm just not seeing? Should I in fact be creating an "extras" directory rather than still sticking things in lib?
If anyone can point me in the direction of a definitive article on the matter I'd be much obliged!
There is nothing wrong with having non active record models in the model folder. If your domain is best modeled by a business logic layer and a persistence layer, then model it that way in your model folder with appropriate naming conventions. Personally I wouldn't be overly concerned with getting it perfect. Try something and see how you like it.. learn from your mistakes and keep getting better! Above all, enjoy the process.
what I do is this: keep the model logic in the model and keep the controllers as thin as possible
If there are things that should belong to your model but are somewhat distant to it (for example you have an Account model and you're working on some payments system which relates to the Account - for example you might want to call account.has_subscription?, you could use a gem called concerned_with which would split your model's main actions from others like the ones handling payments (this is just an example I recently had to take care of).

Ruby on Rails - Best practice / method for loading side column content/blocks

I am developing a community / news article website where there is a side column with different "blocks" on nearly all pages. In these blocks is "Recent Articles (showing five most recent articles)," "Recent Blogs," "Recent Comments," you get the drift.
When I started out building the application, I wasn't real sure where to put the controller code (say, to call #recent_articles = Article.where...etc). I didn't think it could go into the Articles controller, because it's not always the Articles controller being called. So I thought it would work best in the application controller, as most content on the site would be calling this. I put "#recent_content" into the application controller, did a :before_filter to load it.
You might see the flaw in this. As I'm getting better with Rails, I went back to refactor as the site was loading horribly and sure enough, all my logic in the application controller defined by before_filter was being loaded on every action, no matter if it was needed or not. (The site sped up dramatically when I cleaned house on the application controller).
My mistake is realized, but I still need to define the instance variables for #recent_articles, #recent_blogs, etc somewhere, so they load up only when needed. Granted I'll be eventually caching the site content when it goes into production, but I want to be a good Rails programmer here.
So here is my question...exactly how would you handle this situation and where would you put the logic? I can think of two ways, not sure which one is better...
The first way...I took a look at a project from another Rails developer and I noticed he was doing odd things like this by creating files in the /lib folder. For example, defining a method for page meta tags or active menu states. I honestly haven't messed with the /lib folder before, figuring most of my stuff should stay in the /app folder.
The second way...seems to me like helpers might seem the way to go. Maybe I could define a "recent_articles" helper, call my #recent_articles instance variable in there, then render and pass the results to a view file in my shared folder.
Overall, which one of these ways is the better way to go, either from a performance or best-practices viewpoint? Or is there a better way of doing this that I'm unaware of?
Whenever there are many models that can call a particular method, i would probably use a module. I think that is what you are talking about in your first idea, since /lib is where modules are placed.
You can use helpers as well, but it's a good idea to keep logic out of helpers, only in models if possible. Helpers should be just used as a way to present data, they are part of views. If logic is added, then something is wrong :)
Make sure that you do not have logic in your controllers as well. I would be doing the same things in the beginning, but it's really a bad idea. Instead, put everything in your models, or maybe a module if they seem to be used by many other models.
Hope that helps you a bit :)

Helpers in rails

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.

Correct way to optimize repeated Rails code

I have a Rails application with several models-views-controllers which have some similar characteristics, for example 5 different models can be commented on, voted on or tagged, I am also heavily using external plugins.
At the moment I introduced comments, votes, tags, etc. only to a single model (and its view and controller). However, now that I am happy with the results, I want to cut out this common functionality from the particular MVC of one model and allow access to it from all other models.
Some questions before I start doing this (and maybe some general advice will also be great):
1 - How should I go about it? I was thinking creating a module in "lib" directory (is it the same as mixin class?) and then moving reusable view code to common partials. What about the controller code?
2 - As I was just learning Ruby on Rails during the coding of the first model, I went with a probably incorrect way of adding a bunch of methods to the controller. I have a method that adds a comment (addcomment), adds a vote (addvote), etc. All these methods require non-standard (non-RESTful) routing via :collection. From what I understand, the correct way would be to move comments controller functionality to its own controller and access via standard RESTful routes. Is this what I should be doing?
3 - Many plugins (eg. act_as_commentable) do not explicitly require loading a Module, just a line "act_as_commentable" somewhere in the Model. Can I use something like this for my common functionality? How does it work?
A simple way is to split the code into modules and use mixin.
A better way is to write your own plugins for your common code.. like act_as_commentable
you can learn about it here: http://guides.rubyonrails.org/plugins.html
The correct way is to do a comments controller, and have it nested to your models, giving a restful routes like this: /mymodelname/1/comments.
An easy way to make such controllers is by using inherited_resources plugin.
scroll down to the "Polymorphic belongs to" section- there is a comments controller example
For repeated model code, put it in a module in the lib directory.
For controller code, put your duplicate code in ApplicationController.
For your view code, use partials.

Resources