Rails 4.2 Dry up Controller - ruby-on-rails

I have a User model which gets accessed through a REST API and ActiveAdmin. Since there is a lot duplicated code (almost all) it might be a good idea to dry things up. There are a lot of topics out there handling this issue but i do not find a proper way. I put some of the ideas i have below
UserController instance in each controller
Again duplicated code gets created and the functions
#AA
controller do
def create
#userController = UserController.new
#userController.create(params)
end
end
#REST API
#Create instance through callback
def create
#userController.create(params)
end
Inheritance
I would like to have one basic CRUD controller lying above my model through inheritance like this
Class BaseUserController < ApplicationController
Class Api::UserController < BaseUserController
but (yet) i dont know how to do this in AA also in mind with the inherited_resource gem in mind
Concerns
Also concerns seem to be a nice way. But i would then create seperate concerns for each action to have one concern to exactly handle one behaviour
aspect and also to make them more reuseable . This then again seems to unnecessarily bloat the app and also concerns are not really made to be used like that. (?)
Modules/Mixins
Since modules cannot be instantiated but implement actions fully, this might just be what i am looking for. So each controller includes the desired actions or extend fro ma model rather than a class then.
The thing is - the more i read the more i get confused. I hope some of you guys might help me bring some light or i might turn to the dark side an use C# and .NEt again :D
Thanks in advance!
Example Code
I took this create method for a SMS resource in both, the REST API and the AA, where i call a couple of Services, but if complexity grows i have to add these lines in two places. How could i avoid that? Cant i have a basic SMSController which is used from the API endpoints as well as the AA interface?
controller do
def create
#customer =Customer.find_by_phone(params[:sms_message][:phone])
SmsService.sendSMS(#customer[:phone],Cryptoalgorithm.sms(#customer[:id], #customer[:recharge_token],params[:sms_message][:text].to_i)
#sms = SmsMessage.create(:customer_id => #customer[:id], :text => params[:sms_message][:text], :phone => params[:sms_message][:phone])
#customer.increment!(:recharge_token)
redirect_to admin_sms_message_path(#sms[:id])
end
end

Related

Ruby on Rails - Controller without Views

Iam new in Ruby on Rails. Normally I work with other web languages and now (of course) I try to compare it with other languages using on web.
But sometimes i have some problem to understand the philosophy and the character of Ruby on Rails. Of course i understand the concept of MVC.
But now Iam not absolutely sure:
Is ist OK to create and use a controller without views? In some cases you need a "class" for some usefull functionality used by other controllers they have views. Or is it a better style to use a module?
I try to find it out by reading a lot of articles and examples, but didnt find detailed information about this content.
When developing Ruby On Rails apps, it's recommended to put most of your business logic in the models, so for the controllers the logic need to be minimal to provide info for the views, so if it doesn't work with a view chance that you need a controller are really low.
Is it OK to create and use a controller without views
Yep it's okay.
The key thing to keep in mind is that Ruby/Rails is object orientated.
This means that every single you do with your controllers/models etc should have the "object" you're manipulating at its core.
With this in mind, it means you can have a controller without corresponding views, as sometimes, you just need to manipulate an object and return a simple response (for example with Ajax).
--
We often re-use views for different actions (does that count as not having a view):
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def search
render :index, layout: false
end
end
The notion of skinny controller, fat model is sound in principle, you have to account for the times when you may need small pieces of functionality that can only be handled by a controller:
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def update
#user = User.find params[:id]
#user.update
respond_to do |format|
format.js {render nothing: true}
format.html
end
end
end
A very rudimentary example of Rails is a drive-thru:
view = input interface
controller = accepts order & delivers
model = gets order packaged etc in backend
There are times when the controller may not need a view (for example, if you update your order with specific dietry requirements), and thus the notion that every controller action has to have a view is false.
It's really about making your controller versatile enough to manage your objects correctly.
Shared controller methods can be placed in ApplicationController. Also, in Rails 4 there are concerns (app/controllers/concerns/) where you can put the modules with methods that can be used by multiple controllers.
Controller handles request and renders corresponding view template. So controller without view is absolutely nonsense.
Every time request will execute this controller, it will just end with missing template error, so you will need to create view folder and put empty files with action name inside of it, which is obviously stupid.

Using a Decorator, (rails) Could not infer a decorator for ActiveRecord::Base

I'm having trouble using a decorator. I've never used one before and I've been trying to use one with regards to something that I've been doing for breaking up some emails.
However because I've never used one before, I've been having trouble even doing very simple things with my decorator and I'm thinking there is some form of setup issue with it. I do know that everything outside of my little feature (aka the gemfile and such) are all up to date and proper.
The error I am getting is simply,
Could not infer a decorator for ActiveRecord::Base.
Now I have a controller that is almost empty, but inside it, I have the active record portion saved like so.
class Admin::ReceivedEmailsController < Admin::ApplicationController
With my view being titled,
_receive_email.html.haml
All I am doing in my view as of right now is so:
%td= received_email.decorate
My decorator
class Admin::ReceivedEmailsDecorator < Admin::ApplicationDecorator
def received_email
if can? :update, #customer
received_email.content
else
"You need to have the correct admin access to view the email"
end
end
I feel like this would have to be such an elementary thing for me to be missing, but I'm not sure what it is. Would anybody have any idea what I'm missing?
After much further research, reverse engineering further decorators and reading more documentation. I learned that a model or a helper is needed for a decorator to be properly used. Which due to my partial I did not have one specific model or helper to use.

Rails: Is it bad practice to handle CRUD operations for two models in one Controller?

I am working on a Rails project. I was advised to make one controller, the Home_Controller, which would handle the requests of the site. I have two different models, Post and Person (which btw are totally independent). I would like to define methods like new in the Home Controller but it seems against convention to write controller methods like new_person and new_post.
Thanks for your help!
It IS against the MVC pattern, as your Home_Controller should only control the Home model.
You should have a PeopleController and a PostsController to separate your concerns.
That being said - it's not totally unheard of to have the system that you are asking for.. You'll just have to create your own custom routes in routes.rb to match what you want. For example, your HomeController could look like,
class HomeController < ApplicationController
...
def new_person
#person = Person.create
end
def new_post
#post = Post.create
end
end
Routes would look something like,
get 'people/new' => 'home#new_person'
get 'post/new' => 'home#new_post'
the main issue is that when you stray away from this convention, you run into very unreadable and hard to maintain code. especially when you have multiple hands in 1 file.
Going to go ahead and say probably. It's hard to know exactly outside of context, but yes, this would go against convention.
Separate from the convention issue, is maintainability and readability and having one massive controller file would be hell to develop on.

rails 3, is there a way to keep skinny controller when controller uses lots of session info?

I like a nice skinny controller as much as the next guy.
But the app I'm working on talks extensively to a remote system via JSON, and the session variables are used extensively... each little interaction is a separate hit to one of dozens of controller methods, and rails' built-in session tracking keeps track of all the state.
Consequently, the controller has dozens of methods, one for each "interaction" and those methods extensively read (and sometimes write) the session.
It's my understanding that if you're accessing the session in your model methods you're doing something horribly "wrong" ... but having 100+ lines of code PER controller-method for dozens of controller methods seems "wrong" too.
Given that scenario, what IS the best tradeoff between fat controllers vs models that access the session?
I recently came across a similar problem. I was writing and application that depended heavily on a remote API that accepted/returned JSON. Subsequently, I had very few models in my application, and my controllers were quite lengthly.
I ended up writing a custom parser module in lib/ and made calls to the Module (which handled a lot of the logic that would normally exist in the controller)
Consider the following:
module RemoteParser
def get_user(user_id)
result = ActiveSupport::JSON.parse(NetHttp.get('http://www.example.com/'))
session[:received_user] = true
end
end
Now your controllers can be skinny again:
class SomeController < ApplicationController
def index
#user = RemoteParser::get_user(params[:id])
end
end
I'd just like to add that this is an incredibly contrived example of such uses. If you provide additional information about what your requesting, etc, I can help you further.

Using multiple controllers in one view in Rails

I'm working on something like a social networking mesh; I am using different API's from various websites, e.g. Last.FM, Delicious, Twitter, ...
I've created one controller per each website (currently, there are 7).
Sample views:
localhost:3000/lastfm <- All datas i gathered from user's Last.fm account
localhost:3000/twitter <- All datas i gathered from user's Twitter account
...
Now I want to show these datas in one view (localhost:3000/index.hmtl) by using these different controllers.
Components are deprecated, creating one controller and bury all the API's in that seems ugly, too..
So I don't know how to do this. Any idea?
First off, you should put all of the data-storing and data-gathering methods into Resources and Models so they are accessible from all controllers. You can keep the internal data-mutating operations in your individual controllers though. Once you have it organized like this, you could do what Hobo does: create a controller just for the front page, "front_controller" if you will. Here you can display data gathered from all of your models and resources, as well as links to your other controller actions.
These are a few interesting thoughts on better organizing your models and controllers (fat models, skinny controllers is a rule of thumb.
Since you said you are using other API's (like lastfm and twitter), you might want to take a look at this railscasts about creating non ActiveRecord models (models that are not tied to a database)
here is some pseudo code, keep in mind its really only targeted at your question.
# pseudo code
class TwitterController < ApplicationController
def index
#services = {
:twitter => TwitterModel.find(:all, ...),
}
end
def update_twitter
TwitterUpdaterClass.update { |twit|
_m = TwitterModel.new
_m.message = twit.msg
_m.from = twit.from
# ..
_m.save
}
end
end
class MyIndexController < ApplicationController
def index
#services = {
:twitter => TwitterModel.find(:all, ...),
:lastfm => LastFmModel.find(:all, ...)
}
end
end
it might be much better to have background-workers update your rest-services instead a controller which you need to invoke every time you want to fetch recent tweets.
here is nice article showing - 6 ways to run background jobs in rubyonrails
# more pseudo code
class TwitterWorker < BackgrounDRb::MetaWorker
set_worker_name :twitter_worker
def create(args = nil) # instead of TwitterController.update_twitter
TwitterUpdaterClass.update { |twit|
_m = TwitterModel.new
_m.message = twit.msg
_m.from = twit.from
# ..
_m.save
}
end
end
First off, you should put all of the data-storing and data-gathering methods into Resources and Models so they are accessible from all controllers. You can keep the internal data-mutating operations in your individual controllers though. Once you have it organized like this, you could do what Hobo does: create a controller just for the front page, "front_controller" if you will. Here you can display data gathered from all of your models and resources, as well as links to your other controller actions.
I think you should read a bit about rails' MVC architecture.
It seems to me that you are neglecting the M(odel) part of it. The models should hold the data, thus being the most important part of your application.These are a few interesting thoughts on better organizing your models and controllers (fat models, skinny controllers is a rule of thumb. Since you said you are using other API's (like lastfm and twitter), you might want to take a look at this railscast about creating non ActiveRecord models (models that are not tied to a database)
If you also provide an API for your users, I suggest using a RESTful approach, as it can really be easy to develop and maintain once you get the hang of it. You should read more about resources, as your localhost/lastfm and localhost/twitter are resources and not views.
Hope this helps. Good luck

Resources