Loading custom classes in Rails 4 - ruby-on-rails

I'm rewriting one old app - Rails 1.2.6 :)) - completely in Rails 4... so you can imagine the information overload.
It's going quite well so far but I'm currently struggling with one task that should be pretty obvious but it lacks proper documentation and there are just too many blogs with different solutions to this issue.
I have a custom class with custom text conversion functionality (using Redcloth, autolinker, Sanitize etc.), let's call it Textilize class. It's used in models as well as controllers so I guess the best solution would be to create a gem from it. I want to attack gem creation later though since it's just a simple one-file class.
So for now I just added textilize.rb file to /lib directory and added config.autoload_paths += %W(#{config.root}/lib).
It works fine and I can now use it in the app without requiring it in the models and controllers.
Is this a good practice in Rails 4? Is it thread-safe?
If not, is there a way to refactor it without creating a complete gem for now?
Thanks!

"Is this a good practice?" I think it is.
"Is it thread-safe?" I don't know
Any other way? I will use your solution if the lib is crossing Model and Controller and it is simple. If it get rather complex, I will create a plugin. If it is complex and can be extended to be useful on other apps, I will create a gem.

Related

Rails generic controller and views

I've been looking at Administrate source code and would like to know if it's a good practice or not the use of a generic controller and what implications it would have, like code complexity, performance degradation, etc.
Sometime ago, there was a gem inherited_resources that provide this feature, but since Rails 3.0 or 3.1 has been said we no longer need them.
So, since I have some very simple models (with only two or three fields) I could create a generic view and controller to manipulate them and save a lot of lines of "duplicated" code. Although I'm afraid, by avoiding repetition I could be creating another monster.
I've been looking for a Rails way to do this, but failed, so I would thanks some advice.
Note: I'm not looking to implement or use an admin dashboard, but use in my application instead
All Rails admin-panel implementations will make you hurt when you will try to make something more complex than stupid simple CRUD-application. I recomend you not to use such solutions. I had experiece in usage three different Rails's admin-panels and all of them had bad design and a lot of limitations. They are hard to mantain and extend their functionality.

Rails - How to overcome repetitive REST controllers

I've finally started making a Rails app from scratch and I'm getting the hang of it, but the only problem is that making all the models/controllers is getting really repetitive and totally throwing the whole DRY concept out of the window as I'm basically copying controllers and renaming them/adding/disabling fields. I have:
Projects
People
Tasks
Messages
etc and the first three need to pretty much have the same layout and CRUD. Is the only way of not having to manually create all of the actions/views each time scaffolding? If so, what other things does scaffolding generate that I need to be aware of. I've been cautious of using it in the past because I wanted to know how my application worked in the tutorials.
In my opinion scaffolding is not for new rails programmers, it should only be used after you figured out rails yourself and with a criticizing approach. It may generate whole files that you have no need, define unneeded routes etc...
You can have a look at the full details of what scaffold creates here
As for the repetitive controllers you are making I could suggest using the gem InheritedResources which eliminates a lot of this duplication (at least while you are at the basic CRUD controller operations)
InheritedResources sets the basic controller index/show/destroy/create/edit actions for you, all you have to do is to inherit from it using:
class ProjectsController < InheritedResources::Base
end
In case you have to, you can override actions by defining them yourself.
It's an excellent point. You generally want to keep your controllers as thin as possible, and certainly thinner than what the scaffolding gives you.
The way I like to think of the scaffolding is that it's good to use for your first feature in a new Rails app as an example of the current best practices and things you might want to know about. After that, however, write your controllers yourself, and factor out any duplication.
For additional ideas, you might want to read/watch...
Objects on Rails
Hexagonal Rails
Architecture the Lost Years

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.

Hierarchic MVC in Rails 3?

I've read about HMVC (Hierarchic Model View Controller) and it's flexible structure.
Have a look at this picture:
http://techportal.inviqa.com/wp-content/uploads/2010/02/MVC-HMVC.png
I wonder if the Rails 3 plugins are the answer to HMVC in Rails 3?
Based on the comments to Toby's answer it seems that you would like to be able to have MVC apps used as a component within a new app. Rails Engines (See http://rails-engines.org) provides this functionality. You simply install the engines gem and place apps in vendor/plugins and its modles/views/controller are all accessible.
This does not really conform to HMVC where the controllers in the new app delegate to other controllers. But like Toby I do not see the advantage of that.
What is nice about the Engines approach is that you can over ride any of models in the plugin by just adding a version of the model to the new apps app/model folder (same applies for views and controllers)
I have overidden app/views/layouts to give my Authentication app/plugin the same look and feel as the application it is included in.
For Rails 3 Railtie takes the place of engines and is officially supported (and actually used - Action Mailer is a Railtie plugin. I have not used it myself yet though.
Check it out at http://edgeapi.rubyonrails.org/classes/Rails/Railtie.html
A nice write up on it is also here http://www.igvita.com/2010/08/04/rails-3-internals-railtie-creating-plugins/
Rails has had plugins for a long time.
I doubt there is a technical reason why a controller couldn't dispatch to another controller, passing the request object along a chain. I just don't know what you gain by doing so - the diagram looks like spaghetti.
To me it's a misuse of MVC. I would suggest it is much simpler and more maintainable to push logic into lower-level models and classes and create a single controller that fronts the this logic, rather than creating a chain of controllers.
In the Rails 3 blog post, DHH mentioned the Cells project. I haven't used it but I am going to check it out.
The cart example shows well how that kind of functionality might clean up your application code. Code which retrieves data should be placed somewhere in controller. In every action or in a before filter. The Cell seems to be much better solution.
Please look at this rubyonrails-talk post: https://groups.google.com/forum/#!topic/rubyonrails-talk/0c4TT7UOGCw

Does a "vertical" framework for RoR make sense?

I have been spending some time creating what I called a framework.
It was aimed at the creation of quiz likes games. It was supposed to have two players syncronized and present them a question to solve, etc.
I would like it to be fully customizable so I tried to develop components that can be put in or out of the pages. In the end the elements became slim ruby methods to add a whole bunch of Javascript and CSS to the pages.
Still the Javascript needs to connect to Ruby so methods supporting it are created but they will only be present when the component is present. Some components depend on one another making everything overly complex.
And after this attempt I wonder, is there is not a better and easier way to make a framework aimed to one kind of application on RoR? Or is the concept flawed or RoR in some way flawed?
Ruby on Rails is a framework on its own accord and is "opinionated software". This means that the writers of Rails looked at what would make most sense for creating a web application to them. Many people support the original developers views and so use Rails for their projects as well.
I think your concept of creating a quiz is a good one, but first you need to understand the rails stack. Depending on what you need exactly, you can create either an engine, plugin or whatever.
What I have seen a lot is that you specify what you need in your controller. (How you do that is up to you). All that information is stored in a class variable and transferred to the view where you can render everything you need with some helpers. The hard part is making it all generic enough to be reusable.
But, maybe Rails isn't the right tool for you. Maybe you need something more lightweight like Merb or even Sinatra.
There is no 'flaw' in Rails. Rails is not the 10**1000-in-one tool Java is. It's a framework that tries to do one way very good in a particular way. I think Rails can be the right tool for you, but you need to be skilled enough to wield the tool :)

Resources