What to do with my monolithic model? - ruby-on-rails

My user model is about 2k lines of code. I'm sure this is the case for lots of apps. However, readability and even maintainability starts to degrade in models beyond 400 lines of code, in my opinion. So I started to take related code in the user model and organize it in modules in lib. For example, if I had code related to the user's friends, then I created a module called UserFriend and included it in the user model.
Doing this helped solve the original problem. However, the downside is every time I modify code in the module in my dev environment, I gotta restart the server to load it.
So:
Is my original approach to
handling the monolithic model
correct?
What can I do to avoid
having to restart my server to load
code changes in user modules?

There are a few solutions floating around the Internet for how to reload the lib folder automatically in development mode.
One post I found said that if you require files using require_dependency instead of require, the file will be reloaded each request.
Another more "hacky" solution can be found here, and involves adding a before_filter to your ApplicationController.

You can do one thing, Just keep your helper modules in model folder itself instead of keeping in in lib folder OR create a folder in model where you can keep all the helper modules. I don't see any problem with this approach.

Related

Where do I put my helpers and how do I test them?

This is my first on StackOverflow and I'm a new rails developer.
I'm using RoR to create an inventory application for Magic: The Gathering cards. I've found a Json API that I'd like to use to pull data on all of the cards, sets, etc into a local database.
My initial inclination is to create a helper class to manage all of this (which can also be called in seeds.rb during db:setup), but I have no idea where I should put this class in my project's directory structure. It's not really a model/controller/view, so I feel it should be kept separate from those parts of the app.
Further more, I'm having trouble testing any class I do make. I initially created a directory app/classes and put the class there. Then in my spec directory, I created spec/classes and created the spec file. Accessing my helper class from the spec did not work in the same way that accessing my models in their spec classes did.
I'm at a loss as to how to do this and quite a bit of googling and searching on here has just left me more confused. I'd love any help that can be offered. How would you do this?
You don't mention specifically what issues you're encountering, but for starters app/classes isn't in rails's autoload path - rails' require magic doesn't know to look in there to find these classes (as an aside, 'classes' sounds like a slightly meaningless name - models & controllers are classes too).
You can add to the paths rails searches (see config.autoload_paths in config/application.rb) but I would put this in lib (and the corresponding specs in spec/lib).
It would also work just fine with these classes in app/models, whether or not it does there is down to choice. There's nothing that says that files in there have to be active record subclasses - the decision of whether or not this functionality belongs in there boils down to whether it works/feels like a model to you.

guidelines for where to put classes in Rails apps that don't fit anywhere

I'm wondering if there are any best practices about where to put non-standard Ruby files in Rails apps, those that don't fit in any of the default directories (controllers/models etc.).
I'm talking about classes that are used by controllers/models etc., but are not subclasses of any of the Rails base classes. Classes that include functionality extracted from models to make them less fat. Some of them kind of look like models but aren't AR models, some of them look more like "services", some are something in between or something else.
A few random examples:
"strategy" classes that handle authentication with password, via facebook etc.
"XParams" objects that encapsulate params or "XCreator" objects that handle processing of params to execute some complex action that results in creating some AR models in the end
classes that make requests to external APIs or encapsulate those requests and responses
fake models that can be substituted for a real AR model (e.g. guest user)
Resque jobs
classes that store and read information from Redis
classes that execute some specific actions like processing data, generating reports etc. and are called from Resque jobs or rake tasks
I've got quite a lot of these now, some of them are added to lib which ends up as a pile of random classes and modules, some sneak into app/models. I'd like to organize this somehow, but I don't know where to start.
Should only AR models go into app/models? Or is it ok to also put there any domain or helper models? How you decide if something is a model?
Should everything that doesn't fit into app go into lib? Or maybe I should add a few new custom subdirectories to app? What subdirectories, and how do I divide the custom classes?
How do you handle this in your projects? I know every project is a bit different, but there must be some similarities.
Good question - i don't have a concrete answer for you
but I recommend checking out this post
- http://blog.codeclimate.com/blog/2012/02/07/what-code-goes-in-the-lib-directory/
- be sure to read through all the comments
on a current project i have a ton of non-ActiveRecord objects under app/models, it works but not ideal
i put 're-useable' non application specific code under lib
other alternatives I have tried on side projects (say we have a bunch of command objects)
rails is a pain when it comes to namespaces under app, it loads everything up into the same namespace by default
app/
commands/
products/create_command.rb # Products::CreateCommand
products/update_price_command.rb # Products::UpdatePriceCommand
alternate, everything besides rails under src or an app_name directory
app/
src/
commands/
create_product.rb # Commands::CreateProduct
update_product_price.rb # Commands::UpdateProductPrice
I haven't come across a good solution for this, ideally the 2nd one is better, but would be nice to not have the additional directory under app, that way you open app and see controllers, commands, models etc...
You touch on a number of different use cases, and I think that this part is the closest to the "right" answer:
I've got quite a lot of these now, some of them are added to lib which ends up as a pile of random classes and modules, some sneak into app/models. I'd like to organize this somehow, but I don't know where to start.
That's pretty much right on in my book. The one thing you don't mention is extracting various pieces into separate gems. Classes that talk to external services are excellent candidates for extraction, as are strategy classes if they're sufficiently general. These can be private, since running your own gem server isn't hard, and you can then obviously reuse them across ROR apps.
Last and most concretely, resque jobs I stuff into lib/jobs.
My rule of thumb is if it's a model of some kind, it goes into app/models. If not, it probably belongs in lib or some appropriately named subdirectory thereof, e.g. lib/jobs, lib/extensions, lib/external, or the like.
If you're interested, I also wrote a follow-up article about this a bit later summing up what I found: http://blog.lunarlogic.io/2013/declutter-lib-directory/
I place any model classes (like STI subclasses) in apps/models. I place my other classes in lib, as it seems to be the best place to put them. It's easy for me to know where to look. It's also easier for me to group my tests since my model classes are all in one place.
Convention-wise I'm loathe to put helper classes in app/models. If they're presenter classes they belong in the app/helpers. If they're not then lib seems to be the best place for them.
Often my classes find their way into lib in subdirectories where modules with the same name as the subdirectory is responsible for including them. (Rails is very touchy about filenames and classnames when it comes to the autoloader.)
Another option is to encapsulate each module into its own gem and then refer to the gem via your Gemfile. This permits code sharing across projects.

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).

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.

Where to put reusable methods for access by controllers in rails

I have several methods I call from my controllers that feel like they should be pulled out and put into a reusable class, outside of the controller. Where do people usually put this stuff? I know I can put them into my ApplicationController, but that doesn't seem to be a great solution if I think I can use these methods later in other applications.
Also, I have a bunch of utility methods in my controllers that likely won't be used in other controllers, or in the future at all, but I feel like they just bloat my controller a bit. Do people usually move these out someplace for cleanliness or just end up with a huge controller?
I'm coming from Java and Actionscript where I'd just create new util classes for this stuff.
The lib directory is a place you can put modules/classes which can be mixed in or used by controllers (and anything else, really). This can be a place to put code that doesn't fall into other areas (but be careful about making sure lib doesn't turn into a mess itself). Side comments just to keep in mind:
If you know you have a large amount of related functionality that could, or will, be used in other applications, that might be a plugin.
Its also worth keeping in mind that there's nothing wrong with creating a model that is not an Active Record object. So again, depending on what you have, this might make sense as well.
Create a module file in lib directory:
module ControllerUtil
def foo
end
def bar
end
end
Include the module in the controller:
class UsersController < ApplicationController
include ControllerUtil
end
You can create app/modules directory, and create XYZUtils module in it e.g
module XYZUtils
def abc
end
def efg
end
end
and include the module as and when required in Controllers or models etc.
include XYZUtils
You can create different modules for utility functions related to different Models or entities
I won't prefer /lib directory because that should contain the project related code, not app related, e.g tasks etc.
I would keep all the App related code in /app directory itself
Related to Sahil kalra's above answer from 2014:
Rails now has an app/controllers/concerns directory where you can put modules full of helper methods and easily include or extend them in your controllers. I just copied and pasted all of my logic-intensive methods out of my application_controller and they worked right out of the box.
(You should, of course, still make sure everything works correctly before putting anything into production.)
Controllers should be very minimal - basically ingesting arguments and making some very high level decisions. If you have some helper functions that are doing just those kinds of things but aren't going to be reused, then keeping them in the controller is the right thing to do. Just make sure to mark them as private.
For more commonly shared things, you can either back them into your ApplicationController (if they're used in all controllers) or into a class in your app/models directory. I recommend the models directory over lib because Rails in development mode is much better about spotting changes to those files and reloading them. Changes to files in /lib tend to require restarting the webserver, which slows down your development effort. This is unfortunate, because controller helpers really should not be mixed with models.
In general, though, if you have more than a handful of these helpers, you're probably doing too much in your controllers. Take a hard look at them and see if maybe some of them shouldn't be part of your models instead.

Resources