Rails: where to put statistics code? - ruby-on-rails

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/

Related

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!

Where is the best place to put modules that extend your active record models?

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.

Refactor ruby on rails

What is best way to refactor in Ruby on Rails. I have a project where i would like to refactor several of my objects - extra properties and renaming of existing properties. How do i do this this the easiest way?? I created the different objects with scaffolding "rails generate scaffold foo name:string...."
I do start from scratch or is there some cool ruby command, like "rails refactor foo name:string"..
As far as I am aware, there is no automated way to do this. The key things as far as I'm concerned is to make sure that your test coverage is good in the relevant area (and preferably across your whole app) before you start.
Once that's done, I've tended to apply fairly brute force tactics to do that actual refactor:
Run all tests.
Searching for relevant file names and strings within files, making a value judgement as to whether you're changing the right thing (don't just do search/replace).
Refactor your tests along side the code itself.
Run all tests again.
Repeat until it works.
The reason that refactoring isn't very automated in Ruby (in my view at least) is because the language is so dynamic, so it's very hard for any automated tools to make sure they've covered all the bases.
Refactoring is based on human perception. Sure, omission of some redundant things could be figured out by a computer, but otherwise when you refactor you're essentially improving your own hand-written code. Unless a computer has the intelligence and the ability to discern code like a human, then no, it's not possible.
Perhaps you're referring to something else?
You should learn some Rails best practices and use them to refactor your code
Firstly a good knowledge of your application and then start in a procedure and serialize it.
Use helpers to optimize.Methods should be small enough and minimize the possiblity of repetition of codes.
Use application files which helps a lot
You can also write methods in private to reduce the lines in methods.
Alwayz be sure where refactoring is done and its dependencies..
Thanx
.

Your thoughts on using Rails scaffold generators

I'm attempting to learn Ruby on Rails. I'm pretty confident with the basics and writing my own models, controllers and views, although I only know the basics.
Lately I've found that, when I start a new application, most of my models nicely fit into the REST philosophy, and I end up just writing most of the same scaffold-generated code by hand anyways. In a case like this, do you think it would be acceptable to start from using script/generate scaffold for each of my required models, and then modifying code as necessary? The prevailing opinion that I've seen seems to be that the scaffolding is a "newbie trick" and real developers don't use it, but for most applications it seems to create a fair chunk of usable code (as opposed to bad code).
What are your thoughts?
I'm not sure if the culture is really against scaffolding or not, but I, for one, love it.
Now, what I do know is that there was sort of a small backlash against scaffolding for a while. This was because basically every Rails tutorial was basically 'whoa, just type
ruby script/generate scaffolding Post title:string body:text
and you have a blog! Done!'
This not actually being the case, the community started to pull back on using scaffolding as that kind of example, because when you do this, you're not done.
The real power of scaffolding, and the reason that I love it, is for its rapid prototyping abilities. You can generate half of your web site, start coding the back end, and still have a usable interface to actually play around with how everything works without worrying about writing interface code.
I think the idea is that you use it to generate 'generic' code, and then rewrite/refactor it to your specific requirements.
I think there is no problem using the code out of the box generator if it does what you want - as long as you remember what it all does from a security point of view (e.g. don't leave in edit/update/destroy actions if you don't want your interface to allow this)
One thing I like, to avoid lots of duplicate generated code, is the make_resourceful plug in - it abstracts the duplicate default code and lets you override it as appropriate.
Rails' fanatical devotion to choosing smart defaults is exactly why you observe that when you hand write code it ends up looking like the code generated by scaffolding. Personally I really enjoy using scaffolds because there's only a couple of tweaks needed at the end (layouts, CSS, validations, etc etc) for those really basic CRUD type operations.
Even when you get to things that are more complex, it's easy to start from a scaffold and move towards what you want. Definitely not just a newbie's tool.
It is a myth that scaffold is meant only for newbies. It is a great tool to kick start you application really quickly. Of course you will need to modify the generated code to suit your requirements. Having said that, it never hurts to have a ready -made code, most of which will be used as is.

How do you read an existing Rails project?

When you start working on an existing Rails project what are the steps that you take to understand the code? Where do you start? What do you use to get a high level view before drilling down into the controllers, models, helpers and views? Do you have any specific techniques, tricks or tools that help speed up the process?
Please don't respond with "Learn Rails & Ruby" (like one of the responses the last guy who asked this got - he also didn't get much response to his question so I thought I would ask again and prompt a bit more). I'm pretty comfortable with my own code. It's sorting other people's that does my head in and takes me a long time to grok.
Look at the models. If the app was written well, this should give you a picture of its domain model, which is where the interesting logic should live. I also look at the tests for the models.
The way that the controllers/views were implemented should be apparent just by using the Rails app and observing the URLs.
Unfortunately, there are many occasions where too much logic lives in controllers and even views. That means you'll have to take a look into those directories too. Doubley-unfortunate, tests for these layers tend to be much less clear.
First I use the app, noting the interesting controller and action names.
Then I start reading the code for these controllers, and for the relevant models when necessary. Views are usually less important.
Unlike a lot of the people so far, I actually don't think tests are the place to start. I think they're too narrow, too focused. It'd be like trying to understand basic physics/mechanics by first zooming into intra-molecular forces and quantum mechanics. I also think you're relying too much on well-written tests, and in my experience, a lot of people don't write sufficient tests or write poor tests (which don't give an accurate sense of what the code should actually do).
1) I think the first thing to do is to understand what the hell the app actually does. Use it, at least long enough to build an idea of what its main purpose is and what the different types of data might be and which actions you can perform, and most importantly, why.
2) You need to step back and see the big picture. I think the best way to do that is by starting with schema.rb. This tells you a few really important things:
What is the vocabulary/concepts of this project. What does "User" actually mean in this app? Why does the app have both "User" and "Account" models and how are they different/related?
You could learn what models there are by looking in app/models but this will actually tell you what data each model holds.
Thanks to *_id fields, you'll learn the associations between the models, which helps you understand how it all fits together.
I'd follow this up by looking at each model's *.rb file for (hopefully) comments, validations, associations, and any additional logic relevant to each. Keep an eye out for regular ol' Ruby classes that might live in lib/.
3) I, personally, would then take a brief glance at routes.rb as it will tell you two key things: a brief survey of all of the actions in the app, and, if the routes and controllers/actions are well named and thought out, a quick sense of where different functionality might live.
At this point you're probably ready to dig into a specific thing you need to learn. Find the controller for the feature you're most interested in and crack it open. Start reading through the relevant actions, see which models are involved, and now maybe start cracking open tests if you want to.
Don't forget to use the rest of your tools: Ruby/Rails debuggers, browser dev tools, logs, etc.
I would say take a look at the tests (or specs if the project uses RSpec) to get an idea at the high-level of what the application is supposed to do. Once you understand from the top level how the models/views/controllers are expected to behave, you can drill into the implementations.
If the Rails project is in a somewhat stable state than I have always been a big fan of using the debugger to help navigate the code base. I'll fire up the browser and begin interacting with the app then target some piece of functionality and set a breakpoint at the beginning of the associated function. With that in place I just study the parameters going into the function and the value being returned to get a better understanding of what's going on. Once you get comfortable you can modify the functionality a little bit to ensure you understand what's going on. Just performing some static analysis on the code can be cumbersome! Good luck!
I can think of two reasons to be looking at an existing app with which I have no previous involvement: I need to make a change or I want to understand one or more aspects because I'm considering using them as input to changes I'm considering making to another app. I include reading-for-education/enlightenment in that second case.
A real benefit of the MVC pattern in particular, and many web apps in general is that they are fairly easily split into request/response pairs, which can to some extent be comprehended in isolation. So you can start with a single interaction and grow your understanding out from that.
When needing to modify or extend existing code, I should have a good idea of what the first change will be - if not then I probably shouldn't be fooling with the code yet! In a Rails app, the change is most likely to involve view, model or a combination of both and I should be able to identify the relevant items fairly quickly. If there are tests, I check that they run, then attempt to write a test that exposes the missing functionality and away we go. If there are no tests then it's a bit trickier - I'm going to worry that I might inadvertently break something: I'd consider adding tests to give myself a more confidence, which will in turn start to build some understanding of the area under study. I should fairly quickly be able to get into a red-green-refactor loop, picking up speed as I learn my way around.
Run the tests. :-)
If you're lucky it'll have been built on RSpec, and that'll describe the behavior regardless of the implementation.
I run rake test in a terminal
If the environment does not load, I take a look at the stack trace to figure out what's going on, and then I fix it so that the environment loads and run the tests again
I boot the server and open the app in a browser. Clicking around.
Start working with the tasks at hand.
If the code rocks, I'm happy. If the code sucks, I hurt it for fun and profit.
Aside from the already posted tips of running specs, and decomposing the MVC, I also like:
rake routes
as another way to get a high-level view of all the routes into the app
./script/console
The rails irb console is still my favorite way to inspect models and model methods. Grab a few records and work with them in irb. I know it helps me during development and test.
Look at the documentation, there is pretty good documentation on some projects.
It's a little bit hard to understand other's code, but try it...Read the code ;-)

Resources