I am pondering on using a Restful implementation in Rails. I'm asking myself if it's the way to go.
Should I always go for a Restful implementation or not?
I think there really isn't much other option as far as Rails goes. You would just be fighting against all the design decisions and sensible defaults that Rails, as a framework, has already made for you.
Think about all the provided shortcuts for routing, pathing, forms, etc. I think you would end up just spending more time/effort on a non-RESTful implementation.
The first thing to sort out is what REST really means. Fundamentally it is about utilizing HTTP efficiently and correctly. That is, GET requests don't modify anything, PUT requests are idempotent, etc. The notion of uniquely identified resources just sort of falls out of this optimal usage of HTTP. The beauty of REST is that you gain the maximum programmatic benefit out of HTTP, making things like caching, proxying, and automatic retrying able to work fairly well without any knowledge of the application whatsoever. Dare Obasanjo wrote a nice rant on the topic of REST misunderstanding. This contrasts heavily to something like SOAP where you have an heavyweight envelope format that uses HTTP as nothing more than a glorified transport layer.
Now when it comes to Rails REST there is a whole nother thing going on, and that is Rails' convention over configuration. Rails REST is just a thin baked-in layer of tooling to make it easy to define CRUD operations on resources you define. Note that these resources don't need to correspond to ActiveRecord models, and certainly using Rails resource routing is not a pre-requisite for designing a RESTful application. What Rails gives you is an extremely handy default for dealing with things that fit the model of a CRUDable resource, however you shouldn't hesitate to define additional methods on top of resources, or to forego resources altogether if you have pages that don't really seem like resources (eg. reports).
The bottom line to keep in mind is that it's not one or the other. Rails RESTful helpers are using the same primitives that have always been in Rails. You can use both together and they jive nicely.
Related
I've come across two scenarios with regards to creating a REST API in Rails and I wonder which one is preferred. Usually
if you know that you're required to have a REST API for your application at start. Does it make sense to have it in a namespace and thereby duplicating the controller logic?
I've seen examples where people have an application already and later figure they need to extend and offer a REST API. The approach to this has been to create new routes with namespacein routes.rb and controllers/api/whatever.... This still yields duplicate code though, but might be more sensible approach. The difference being a stateless machine for the REST API calls.
Can anyone elaborate on the preferred approach, thanks.
If you create a Rails application, and following the usual conventions, you basically end up with a REST API. Unless you are talking about a more specific meaning of the term (which I am not aware of), "REST API" is more a bunch of general characteristics of the API (i.e., things like statelessness, resource-based URIs if using HTTP, etc.).
So to turn the question right back to you: which case are you thinking about where a (conventional) Rails application is not by extension trivially a REST API?
I've been reading up on REST lately and it's become seemingly clear that verbs do not belong in URIs. If this is the case, is the standard "resource/1/edit/" that particularly shows up in Rails a violation of REST? And if so, what alternatives are there?
Don't confuse CRUD with REST.
Rails provides "Resourceful Routing", and the actions within the URL simply provide a resourceful interface. The HTTP request verbiage still remains RESTful, which is what counts.
Here is an insightful article which does a fairly good job explaining REST/CRUD (specifically in Rails).
I'm pretty new to Rails 3 and I'm trying to understand the advantage of designing an application in a RESTful way. I don't need an API/Web Service. Don't need XML or JSON.
The application I'm building uses no CRUD at all. It is an app that gathers trade data via a socket connection and displays it to a user in many different ways.
I would like to visualize trades in different ways such as:
Most recent
Highest Yielding
Trades by State
Most active trades
Million dollar trades
Trades that are general obligation bonds
etc…
In the "Rails way" it seems that I would have a very overloaded index action. Or I could go against convention and just create methods in the trades controller like most_recent, highest_yielding, most_active, etc. But that seems to go against the whole philosophy of designing an app in Rails 3.
It just seems like the idea behind a RESTful approach in Rails is based around CRUD and falls short when CRUD isn't involved. Is there really an advantage to designing your app to be "RESTful" besides following a convention? I'm not really seeing the advantage here.
Plus, if I ever do need an API, I would imagine that it would be much better to design an API with an API in mind. My API wouldn't be a direct 1 to 1 match of my website which is built for human consumption vs a machine.
I'd appreciate any insight on this. Maybe I'm missing something here?
CRUD is actually involved when resources are involved. And since virtually every application has resources CRUD can be involved and is usually(if you ask me), the best way to do it.
The idea is that a resource has certain actions. You view a resource, you edit it, you delete it and some more. The methods like most_recent(or scope for this one) should be used in models and not controllers. Then, if you need to use that collection, you would just call something like :
#recent_posts = Post.most_recent
in your controller. Your controllers should not have much code, actually no business logic at all.
RESTful is very nice because it handles resources naturally. A controller should actually be handling a resource. If you think that something can be edited or created, then it should be handled by a controller.
Generally, i highly suggest that you take a deeper look and you will definitely see the advantages on your own.
I have idea how to do it. Code is not tested, I just wrote it without running.
Controller:
# trades_controller.rb
def index
# all scopes defined in model will be allowed here
# not good idea if you don't want it
if Trade.scopes.has_key?(params[:scope].to_sym)
#trades = Trade.send(:params[:scope])
else
# render error or what you want
end
end
Model
# trade.rb
scope :most_recent, order(:created_at)
# more scopes
View
# index.html.erb
link_to 'Most recent', trades_path(:scope => 'most_recent')
Your design should always take into account the requirements of your application first and the philosophy of the framework second.
If the philosophy doesn't fit your requirements or what you believe is the best way to develop your application then either ignore it, or, if the framework makes it too difficult for you to build like you think you should (which isn't the case in Rails imho), switch to another framework.
All of that doesn't have much to do with REST. For more info on why REST is considered a good idea (for some, not all, things), see the following SO Q&A's: Why would one use REST instead of Web services and What exactly is RESTful programming.
I've been messing about in rails the past 2 months and so far everything's going well - but there's one area I'm a little doubtful on.
I keep hearing about the joys of RESTful rails resources: that is, a 'resource :foo' in config/routes, and your 7 restful actions in the controller.
Except for very simple things (eg stuff that's 99% done by running 'generate scaffold'), I find it's less convenient to try squeeze my project functionality into that approach than to just match urls in config/routes one-by-one and do each action as needed.
But I keep getting the sense that I'm wrong, and that in all but the most extreme circumstances, RESTful resources are the way to go.
So:
(a) Can anyone offer an opinion on this?
(b) For experienced rails folks, what % of your routes in a typical project are :resources and what % are coded action-by-action?
Cheers...
Resources are convenient, but they are not a "one size fits all" feature. Some things just don't make sense with the 7 methods.
Keep in mind that you can:
Exclude specific methods with :except.
Include only specific methods with :only.
Add your own methods to the resource.
So they aren't as inflexible as you may think. But if, after taking those 3 points in mind, the resource just doesn't "feel right", skip it! REST was never meant to replace regular routing, it just tries to abstract away the most common use case.
If you skip out on RESTful resources completely, you'll be missing a ton of free functionality. Use it wisely and you'll be fine.
Generally I start a project with the REST architecture in mind. I build out my basic functionality this way, but as the project/website progresses I write more and more views that do not fit into the RESTful architecture. Marketing sites and parallel functionality are perfect examples of this.
Here is an article on the approach:
http://ablogaboutcode.com/2010/11/22/to-be-or-not-to-be-restful-ruby-on-rails-best-practices/
Before you get started, here are some questions you might want to ask yourself:
Does this controller/view deal primarily with an object/entity like a Post, Blog?
Are create, update, delete, edit and new actions all going to be available on the web?
As a guideline, if you answer YES to these two questions, then it’s probably best to start with REST and expect that you will eventually use the architecture as a building block for additional actions and views you might want to perform. Otherwise, pick a URL that best represents what the action will show or do (/archives, /tour, /december-offer) and make sure you use the proper HTTP Protocols (GET for display, PUT for update, DELETE for removing and POST for creating).
This is a bit of a weird meta-programming question, but I've realized that my new project doesn't need a full MVC framework, and being a rails guy, I'm not sure what to use now.
To give you a gist of the necessary functionality; this website will display static pages, but users will be able to log in and 'edit their current plans'. All purchasing and credit card editing is being handled by a recurring payment subscriber, I just need a page to edit their current plan. All of that will be done through (dynamic) XML API calls, so no database is necessary.
Should I stick with my typical rails/nginx stack, or is there something I could use that would lighten the load, since I don't need the Rails heft. I'm familiar with python and PHP but would prefer not to go that route. Is Sinatra a good choice here?
tl;dr: What's a good way to quickly serve mostly static pages, preferably in Ruby, with some pages requiring dynamic XML rendering?
If you want to stick with Ruby, Sinatra would be fine, as would Rails Metal.
If you're feeling a bit adventurous and want to get some useful experience with the technology that rails uses you could try building a Rack application. It's a pretty simple API to be able to respond to generic HTTP queries, and from there you can quickly build static file handling and XML processing. It's also considerably faster to start up and serve pages than rails.
http://github.com/cloudhead/toto is an example of a decent Rack based application.
If you know Rails, then why not just stick with it? That way you can use all authentication features, etc. that you're used to without having to learn another platform and incur the implementation risks that that includes. If the application ever grows beyond what's expected you're already on a solid base.