Where is the best place to put modules that extend your active record models? - ruby-on-rails

Just a quick question that strangely I can't find anywhere (maybe I'm wording the question wrong when I ask google)... I have some shared functionality across a few models, but not shared in any way that I'd want to make an actual class to extend, just small utility methods that I'd like to mix in. Where is the "best practice" place to put these kinds of modules?
I can put them in ./lib, but that feel wrong for some reason, I'm not sure. Where's the typical place to put this stuff?
Edit: I see why ./lib felt wrong now. I didn't realize that in rails 3 it no longer autoloads ./lib by default, so I though this had moved elsewhere. Which I guess it has in the sense that it's now up to you. Thanks!

We try to "name" these kinds of things and put them somewhere as appropriate. For example, "concern" is a common name for mixins that provide a specific functionality as a module mixin, so we put them in app/concerns. (In fact, I believe this is a default folder in Rails 4). You may need to adjust your autoload path appropriately.

./lib is an appropriate place. You could namespace these similar modules together, under say, ./lib/active_record_mixins/

There is no "best" place, at least as you describe your mixin.
It was always up to you; you can add whatever you want to your list of autoloads.
I don't see why lib doesn't "feel right", it's as good as any other. Some types of mixins have names, like "concerns" and "decorators", but it's not clear if what you're mixing in falls into that broad a category.
Autoloading of everything under lib was turned off to control autoloading, not because it wasn't an okay place to put libraries. For modules that don't fit into a broad, app-wide category (think "decorators" or "concerns") lib seems perfectly reasonable.
Autoloading means you have to use require instead of everything being loaded everywhere; this isn't necessarily a Bad Thing, IMO.
Because it depends entirely on the nature of the code, the structure of your app, and how you want to structure your app, I'm not convinced there's an open-ended "best" practice.

Related

Why Model View Controller in their own namespace?

This might be a bit of a noob question, but I'm curious why the convention for MVC classes is to be in their own namespace, eg
namespace WebApplication1.Controllers
and not
namespace WebApplication1
Is there a good syntactical reason for this or is it just to improve readability?.
Is it perfectly ok to not follow this convention and use the same namespace for the whole project?
You can use namespaces any way you like, as long as it makes sense to you.
What they've done there is simply a convention deriving from the separation of concerns part.
Are their disadvantages to this method? Well yes, separate too much and your classes become a mess with too many using statements.
If you put too much under one namespace that can also cause issues because you don't know exactly what's available to you and it makes finding anything difficult.
If your namespaces follow your folder structure then it can help keep your code nicely organised and everything is easy to find just by looking at the namespace.
It is possible, but namespace are there for minimizing classes name conflicts, which if you handling middle+ projects you will encounter.
More on Namespaces
They also help the Intellisense display current available entities, but this is just a bonus and not the actual target of name spacing.

Good or bad idea to prefix all classes with same abbreviation?

So in practically all my programs I wrote I always prefixed every class I created with the same abbreviation that was in relation to the program. So for instance say I wrote an app called GasStationDeluxe. I would make a class called GSDGasStation or GSDGasPump etc. Now I always thought that is a good idea because it would group together all thelse classes I created in intellisense to make it easier for me and other programmers to find the classes I created.
Yet, I'm reading a book called "Clean Code: A Handbook of agIle software craftsmanship" and I just read a part in a chapter where it says it's not a good idea to do that becasue auto complete will bring you back a list of tons of classes. So who else codes this way? Do you think it's a good or bad idea to code with the same prefix before each class? If yes or no, then why?
I have never done this, but you will sometimes see it done in solutions with multiple projects like GSD.App or GSD.Core
I was always that in a class called Customer.cs, you might not want to make the name field CustomeName but just Name as your already in the customer class so what is it adding. I suppose the same is true in your case of classes.
What if you want to reuse your classes elsewhere? I would say from the vast majority of code examples I come across and other peoples code I read, this isn’t common practice.
I suppose really it’s up to you and any team you work with, as long as it’s consistent.
I wonder what .net would look like if Microsoft prefixed everything!

When should you nest model declarations in Rails?

What are the guidelines about when it is better to nest Model name spaces and when it is better to leave them all top-level?
For instance, when I have a few classes that all have something to do with one core class (and the majority of the system only deals with that core class) then my instinct tells me to declare them as such:
CoreModel
CoreModel::DependentOne
CoreModel::AnotherDependent
Almost always this corresponding to has_many/belongs_to relationships (i'd almost consider this the next candidate for convention over configuration.)
And again, my routes often reflect this nesting:
/CoreModels/:core_model_id/DependentOne/:id
The reason I feel like I should do this is because often two component areas of the same large application may need a supporting component with similar if not identical names as other areas of the software. I feel like name spacing these dependent models (which only exist to support that core model) is the best way to go.
I'm confused because while some times doing things this way can make stuff easier (such as link_to which needs only to take the DependentOne model and will automatically route correctly) yet other items such as form_for refuse to work properly (because it doesn't route properly and if I add the CoreModel to the form_for it complains about no such route core_model_core_model_dependent_one etc....
Perhaps I haven't been clear enough and so I'll ensure I update this as requests for clarifications come in.
...the majority of the system only deals with that core class...
In that case, I wouldn't bother namespacing them.
The reason I feel like I should do this is because often two component areas of the same large application may need a supporting component with similar if not identical names as other areas of the software. I feel like name spacing these dependent models (which only exist to support that core model) is the best way to go.
Bingo - if you have name conflicts, namespacing is a good way to fix it. But, do you have that problem yet?
Namespacing prevents name conflicts, but in Rails it also introduces some gotchas and headaches and (throughout the app) quite a bit more typing. So, to me, it isn't worth it unless you actually have a name conflict.
Consider a structure like this, with your core model and many that just help it.
#Core Models
Model
Supporter
Assister
Helper
Benefactor
For most of the life of your app you may never run into a problem. If you do finally hit one, you could just do this:
AltModel
AltModel::Supporter
OtherModel
OtherModel::Benefactor
Or if it's really simple just prefixing the class name would work:
AltModelSupporter
OtherModelBenefactor
For that matter, it's probably simpler to name your core models in this way than it would be to "properly" namespace them:
CoreModel
CoreSupporter
CoreAssister
So, there are many ways to accomplish what you need, none of which suggest you should bother namespacing the core functionality of your app when you don't actually have a namespace conflict. Given the headaches you've already run into I think you'll be happier leaving the core models of your app in the top-level namespace and only nesting alternate models that actually have a conflict down the road.

Rails: where to put statistics code?

I have a Rails app that uses a lot of custom statistics code I wrote, things like calculating the mean and standard deviation of an array of numbers, or calculating statistical significance tests.
Where do I put all this code? It's not tied to any database object, so I'm guessing it shouldn't go into /models. And if I understand correctly, /app/helpers is only for helper functions called from your views, so I don't think it should go there. Am I supposed to put my statistics code into /lib?
In general, I'm not sure where I'm supposed to put helper libraries that are called from my models.
As an aside, you can definitely have models that aren't tied to database tables, but they should still be classes that represent "things" in your domain, in my opinion. So I still wouldn't put them in /models, but not because of anything to do with the database.
I would put them in /lib, yes. Note that they won't be loaded by Rails automatically, so you'll want to add require statements in an initializer.
If this code is only useful for this project, then /lib is a good place. However, you might also consider packaging it into a gem if you think you might use the code in another project later on, especially if you're going to have more than one project using this code at the same time.
/lib sounds good for these stuffs
Agreed, putting your code into a module that can be included into your models is the way to go. That usually goes into lib/

How do you make code reusable? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 2 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Any code can be reused in a way or an other, at least if you modify the code. Random code is not very reusable as such. When I read some books, they usually say that you should explicitly make the code reusable by taking into account other situations of code usage too. But certain code should not be an omnipotent all doing class either.
I would like to have reusable code that I don't have to change later. How do you make code reusable? What are the requirements for code being reusable? What are the things that reusable code should definitely have and what things are optional?
See 10 tips on writing reusable code for some help.
Keep the code DRY. Dry means "Don't Repeat Yourself".
Make a class/method do just one thing.
Write unit tests for your classes AND make it easy to test classes.
Remove the business logic or main code away from any framework code
Try to think more abstractly and use Interfaces and Abstract classes.
Code for extension. Write code that can easily be extended in the future.
Don't write code that isn't needed.
Try to reduce coupling.
Be more Modular
Write code like your code is an External API
If you take the Test-Driven Development approach, then your code only becomes re-usable as your refactor based on forthcoming scenarios.
Personally I find constantly refactoring produces cleaner code than trying to second-guess what scenarios I need to code a particular class for.
More than anything else, maintainability makes code reusable.
Reusability is rarely a worthwhile goal in itself. Rather, it is a by-product of writing code that is well structured, easily maintainable and useful.
If you set out to make reusable code, you often find yourself trying to take into account requirements for behaviour that might be required in future projects. No matter how good you become at this, you'll find that you get these future-proofing requirements wrong.
On the other hand, if you start with the bare requirements of the current project, you will find that your code can be clean and tight and elegant. When you're working on another project that needs similar functionality, you will naturally adapt your original code.
I suggest looking at the best-practices for your chosen programming language / paradigm (eg. Patterns and SOLID for Java / C# types), the Lean / Agile programming literature, and (of course) the book "Code Complete". Understanding the advantages and disadvantages of these approaches will improve your coding practice no end. All your code will then become reausable - but 'by accident', rather than by design.
Also, see here: Writing Maintainable Code
You'll write various modules (parts) when writing a relatively big project. Reusable code in practice means you'll have create libraries that other projects needing that same functionality can use.
So, you have to identify modules that can be reused, for that
Identify the core competence of each module. For instance, if your project has to compress files, you'll have a module that will handle file compression. Do NOT make it do more than ONE THING. One thing only.
Write a library (or class) that will handle file compression, without needing anything more than the file to be compressed, the output and the compression format. This will decouple the module from the rest of the project, enabling it to be (re)used in a different setting.
You don't have to get it perfect the first time, when you actually reuse the library you will probably find out flaws in the design (for instance, you didn't make it modular enough to be able to add new compression formats easily) and you can fix them the second time around and improve the reusability of your module. The more you reuse it (and fix the flaws), the easier it'll become to reuse.
The most important thing to consider is decoupling, if you write tightly coupled code reusability is the first casualty.
Leave all the needed state or context outside the library. Add methods to specify the state to the library.
For most definitions of "reuse", reuse of code is a myth, at least in my experience. Can you tell I have some scars from this? :-)
By reuse, I don't mean taking existing source files and beating them into submission until a new component or service falls out. I mean taking a specific component or service and reusing it without alteration.
I think the first step is to get yourself into a mindset that it's going to take at least 3 iterations to create a reusable component. Why 3? Because the first time you try to reuse a component, you always discover something that it can't handle. So then you have to change it. This happens a couple of times, until finally you have a component that at least appears to be reusable.
The other approach is to do an expensive forward-looking design. But then the cost is all up-front, and the benefits (may) appear some time down the road. If your boss insists that the current project schedule always dominates, then this approach won't work.
Object-orientation allows you to refactor code into superclasses. This is perhaps the easiest, cheapest and most effective kind of reuse. Ordinary class inheritance doesn't require a lot of thinking about "other situations"; you don't have to build "omnipotent" code.
Beyond simple inheritance, reuse is something you find more than you invent. You find reuse situations when you want to reuse one of your own packages to solve a slightly different problem. When you want to reuse a package that doesn't precisely fit the new situation, you have two choices.
Copy it and fix it. You now have to nearly similar packages -- a costly mistake.
Make the original package reusable in two situations.
Just do that for reuse. Nothing more. Too much thinking about "potential" reuse and undefined "other situations" can become a waste of time.
Others have mentioned these tactics, but here they are formally. These three will get you very far:
Adhere to the Single Responsibility
Principle - it ensures your class only "does one thing", which means it's more likely it will be reusable for another application which includes that same thing.
Adhere to the Liskov
Substitution Principle - it ensures your code "does what it's supposed without surprises", which means it's more likely it will be reusable for another application that needs the same thing done.
Adhere to the Open/Closed Principle - it ensures your code can be made to behave differently without modifying its source, which means it's more likely to be reusable without direct modification.
To add to the above mentioned items, I'd say:
Make those functions generic which you need to reuse
Use configuration files and make the code use the properties defined in files/db
Clearly factor your code into such functions/classes that those provide independent functionality and can be used in different scenarios and define those scenarios using the config files
I would add the concept of "Class composition over class inheritance" (which is derived from other answers here).
That way the "composed" object doesn't care about the internal structure of the object it depends on - only its behavior, which leads to better encapsulation and easier maintainability (testing, less details to care about).
In languages such as C# and Java it is often crucial since there is no multiple inheritance so it helps avoiding inheritance graph hell u might have.
As mentioned, modular code is more reusable than non-modular code.
One way to help towards modular code is to use encapsulation, see encapsulation theory here:
http://www.edmundkirwan.com/
Ed.
Avoid reinventing the wheel. That's it. And that by itself has many benefits mentioned above. If you do need to change something, then you just create another piece of code, another class, another constant, library, etc... it helps you and the rest of the developers working in the same application.
Comment, in detail, everything that seems like it might be confusing when you come back to the code next time. Excessively verbose comments can be slightly annoying, but they're far better than sparse comments, and can save hours of trying to figure out WTF you were doing last time.

Resources