Benefits of Sinatra for a web service like controller - ruby-on-rails

I am writing a simple ruby controller that just needs to respond as a webservice to a bunch of mobile clients.
Someone told me I should look into Sinatra. What is the point of using Sinatra for something this simple? He mentioned that it would be "faster" but how can a wrapper on top of something make it faster?
I don't want to overcomplicate things; a simple controller is so easy to write and there are less gems to maintain. Am I missing something that Sinatra offers that makes it worth the extra trouble?
Thanks

The simplest useful Ruby web application you could build would be a Rack application. Sinatra is a lightweight DSL which sits on top of Rack to make coding the controllers and views more convenient. You can build more sophisticated applications by including more add-ons like ActiveRecord or Rack::Oauth, etc
Rails 2 is a more feature rich framework which includes a plethora of additional features already in the framework. Some applications don't need all that so some developers prefer things like Sinatra which is minimal.
However the distinction between Rails and Sinatra has blurred quite a bit since Rails 3. The new version allows everything from just Rack to full Rails in the stack to you can tailor it to suit your needs. The raison d'etre for some of the intermediate frameworks such as Sinatra is weaker than it used to be.
So take a look at Rails 3, start minimally and grow to suit your needs.

Sinatra is a very slim web framework. It needs way less memory at runtime than Rails. Also, request processing is probably faster since there's less code involved. So it can be very appropriate for a webservice "this simple".
Especially if you need to run many instances (e.g. high traffic or many long running requests), this can be an important factor to the number of machines you need to run your webservice.

Related

Clarifications about Rails and Node.js

Up to now I've always used PHP with or without a framework but a month ago I decided to start something new: Ruby and Rails, I found them quite easy and similar to PHP and some PHP frameworks in how they works but using a simpler syntax and many other advantages.
Some days ago I started reading about Node.js, Node.js vs Rails, "why node.js is better"...
I'm a bit confused but my objective is to learn something modern that will not become obsolete in a few months so:
What are the main differences between Rails/Ruby and Node.js and a framework based on it like Express.js (except that one is written in JS and the other in Ruby)?
What are the main advantages/disadvantages of using Node.js and framework based on it instead of a Ruby based solution like Rails?
Thanks!
There aren't enough differences between Node.js and Rails for it to practically matter.
A lot of what Node.js can do can be pulled off in Rails with things like EventMachine and Pusher. So unless you are really familiar with Rails' limitations, and know you'll be pushing the boundaries, you'd be hard pressed to make something a seasoned Rails developer couldn't do.
Having built apps in Node and Express I can say that they alone aren't enough to make a sexy application. They can seem just as old and stale if you don't have an outstanding frontend UI to facilitate the backend possibilities. Instead of comparing backend servers, I think the real future of doing amazing things is in front-end JavaScript frameworks like Backbone.js that use Express/Rails/Node.js on the backend.
I have chosen to go in the direction of Backbone.js with Rails as my backend API server. Because it's so easy to rapidly create a very nice RESTful backend server in Rails. Rails also makes working with CoffeeScript and precompiling/organizing Backbone code a breeze. There are already decent Backbone.js gems out there for Rails.
The Rails core is also able to acknowledge and embrace the fact that frontend JS MVCs are logically a good next step, and they have been working to strengthen the bond between the two. For those same reasons they have also worked to make Rails an even better API server so that it can work with frontend JS easier. Node.js and Express aren't putting as much effort to coordinate with frontend JavaScript MVCs as the Rails community is.
Being good with a JavaScript frontend MVC and Rails as a backend makes you also great for both worlds in terms of getting a job. You will easily be able to hop onto a Node.js project and add value to that team with your superior frontend experience, and you can also roll with the punches on a Ruby on Rails team and add value to them as well.
As official Node.js website explains it:
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
On the other hand Ruby on Rails official website says:
Ruby on Rails is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.
Given this I guess that it is more appropriate to compare Ruby and Node.js, but even this is not quite right given that Ruby is programming language and Node.js is NOT. You could probably compare JavaScript with Ruby but I guess that is not what you meant to ask with this question :)
So, for me, key point in understanding what Node.js truly tries to accomplish is well described on Node.js about page. Key Node.js idea (for me) is described in this sentences:
Node is similar in design to and influenced by systems like Ruby's Event Machine or Python's Twisted. Node takes the event model a bit further—it presents the event loop as a language construct instead of as a library. In other systems there is always a blocking call to start the event-loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blocking call like EventMachine::run(). In Node there is no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there are no more callbacks to perform. This behavior is like browser javascript—the event loop is hidden from the user.
What this should enable you, is that you should be able to easily write highly concurrent programs without even thinking about concurrency using JavaScript syntax and callback functions as basic concurrent runnable units.
Your fear that either Rails or Node.js will be gone in a week is unfounded. Rails has a large community and will be around for a very long time even though currently (early 2012) it's getting a bit of hate thrown its way. Node.js is just getting started and has so much attention I don't think it will have any problems getting to the Rails level some day.
That said I've been evaluating Node.js and Rails as options for a project and the reasons I choose Node.js over Rails are:
"The Rails Way" - In my (admittedly limited) experience with Rails it really seems like you either do it the Rails way or you are going to be in for a world of pain. A big part of the Rails way is to use the ActiveRecord model. The advantage of this is that there are a lot of gems that work with your code happily because they know you'll be using ActiveRecord. The disadvantage is you are mixing your data access & model. I am not a fan of this idea so the Rails way for me still seems a bit.. off.
JavaScript is a key part of client side web development and the idea of using it on the client and server is interesting. I'm not super strong at JavaScript and I can't imagine a better way to get better then to have to use it everywhere.
My project has real time communication needs which while I'm sure can be done in Rails there seems to be quite a bit of positive mention on Nodes ability to handle this with socket.io being the front runner option.
At the end of the day no matter which you choose you will have a great time & learn a ton of new stuff that will change how you write code. If you're not on a big time crunch I'd recommend building a small project management tool in both and see which you prefer.
Either way.. Good Luck!
2 things - performance & productivity.
Performance (more details here)
(source: jslang.info)
Productivity (how fast you can build that app)
Ruby on Rails is specialized and highly productive tool for creating so called Web 1.0 and Web 2.0 applications (99% of internet sites are such apps). In my subjective judgement and experience in this area Rails about 2-4 times more productive than node.js or express.js.
For Web 3.0 apps (realtime things, client-side MVC, etc.) this isn't true, RoR doesn't keep its advantage there.
So choice depends on use case and priorities.
I know a lot more about Node.js than I do about Ruby. That being said, Ruby is much more widely adopted. It is currently a very hot skill to have in the work place. Some may argue with me on this but I think that Node.js is still "under development" and will be for a little bit longer. It has a lot of promise but just hasn't been adopted by many companies and projects yet.

Suitability of Rails, Padrino, and Sinatra for building a prepaid mobile service

I am working on an application in the Mobile/VOIP domain. This is really a gray area for me. Here are some details about the application:
This is basically like an auto recharge / prepaid mobile service
Will have logic of medium complexity compared to previous ERP apps I've written.
The Views sections in the response will be plain text, which will be sent as SMS/USSD pull to user and Voice XML (VXML) that will be sent as an IVR Response to users.
The routing logic is very simple, as only two to three URLs will be important for each type of reply.
Constraints:
We have the core system built in Perl (it's a legacy system which is serving many other VOIP/Mobile-related services), and an accounting system to keep track of profit and loss, but it has grown very complex. So we decided to make this application separately, and only use SMS/USSD and IVR. However, every user of this application has to be a registered user of the core system for accounting purposes; this we can easily achieve by just an API call.
Now, for sending a reply/response for IVR and USSD, we need to deploy the application at the vendor which provides these facilities. But we don't want to always need to log-in to their servers for daily reports and accounting stuff as, for each of our clients, we will have different flows for the USSD/SMS/IVR System.
So, we decided this new application will be indeed divided into two sub-applications.
One application will handle the USER Interface with USSD/SMS/IVR domain and will be deployed on vendor's servers, which we will call "clientware".
The second application will handle all core business logic and reporting systems and will be deployed on our servers, where we will have full access. We will call this "middleware".
The basic flow of the application:
The user dials the shortcode.
Call lands on our vendor servers where clientware app will handle the request and register it as a user in its local database.
Clientware will also make an API call to middleware. To register this user over there as well for core business logic timely auto recharge, etc.
The middleware will then also make API call to the core system to register this user over there as well for accounting purposes.
Now, there will be many such clientware applications interacting with a single middleware application. We have decided to build these applications in Ruby. I would be following RESTful architecture for this, as lots of API calls are involved.
Of the three frameworks, Rails, Padrino, or Sinatra, are any of them specially suited for this project? I would appreciate a good comparison detailed relevant pros and cons, if possible.
I am one of the creators of Padrino but I have also worked extensively with Rails and Sinatra. Probably not what you want to hear but no matter what you pick, you will be able to get this project finished fairly easily. I can't say picking one will impact you much over picking any other in the grand scheme.
I am obviously a proponent of the modular and lightweight nature of Rack and Sinatra. Between Rack, Rack Middlewares, Sinatra and extensions, you can get anything done just as easily as in Rails if you are willing to understand the tools.
I would argue that Sinatra and Padrino have a lower learning curve to Ruby newcomers. This is because they promote "take what you need" and "gradual complexity" far better than the more "take it all at once" Rails approach but on the other hand Rails has much more documentation, blogs, support, etc. So the trade offs are clear. Sinatra and Padrino are also much "faster" and "lighter" in terms of memory footprint, requests per second, cpu usage, etc but Rails is fast enough for most situations and the application server is rarely the bottleneck anyways.
All that said, I will try to give you a more direct opinion. If you are doing nothing but a service API (which it sounds like here), I would recommend using Sinatra, Padrino or even another project of ours Renee over Rails. Rails is overkill for a lightweight service API by most measures.
Narrowing it down further, Padrino is Sinatra so you don't have to choose between them. You can start with Sinatra and include standalone modules from Padrino, or use a full-stack Padrino application which is still Sinatra under the hood with a very minimal performance penalty for access to a lot of powerful features (i18n, logger, admin panel, caching, generators, form helpers, mailer, etc). Keep in mind these are all "take them only if you need them" modular extensions.
I would recommend checking out our Padrino Getting Started guide for a place to start exploring Sinatra and Padrino. Our Padrino guides and documentation strive to be thorough. That said, the "safe" bet is Rails since it has a lot more usage, it is more mature, has more contributors and a lot more documentation / googleability. Good luck, hope this was helpful.

Alternatives for Ruby on Rails and/or its components

I'm curious about alternatives to the components of RoR or RoR itself.
Some research brought up the ORM alternatives to ActiveRecord here on SO.
So remaining is the question about alternatives for...
... the controllers (ActiveController)
... the views (ActiveView)
... RoR itself
... any other component I'm missing here :D
Really, I'm very happy with all of them, but I'm asking out of pure curiosity.
In place of ActiveRecord, there are a few to choose from. The biggest competitor (and my favorite) seems to be DataMapper, then there's Sequel, Mongoid, MongoMapper. There are plenty of others too, but these are relatively big players.
In place of ActionView (not Active... Action... confusing, I know), I haven't come across anything. I've seen plenty of additions to it, but no complete replacements. I guess that means people are mostly happy with ActionView. Now, there are other template-engines available though. The big player here is HAML. Using HAML doesn't mean you're not using ActionView though. You're still using ActionView, just with a different template pre-processor.
Alternatives to RoR itself. Again, there are a few. The big players are Sinatra, Merb (which started in the early Rails days by some people who disagreed with a thing or two in Rails, and then Rails learnt a thing or two and took some bits and pieces back again... confusing!). There's also Ramaze, but I don't know much about it.
The thing is, Rails is more or less unrivaled in what it does. If you get your hands on a web app written in Ruby, it's probably going to either be a Rails app or a Sinatra app. Sinatra meets a different need to Rails. Rails wants to provide you with a whole array of tools to get things done quickly, while Sinatra's main goal is to be lightweight and keep out of your way. Rails is huge, while Sinatra basically boils down a glorified route map/dispatcher (I mean this in a good way), leaving you to build your web app however you see fit. Sinatra makes it easy to package a small web admin tool inside a gem, for example. You probably wouldn't want to include a Rails app inside a gem. That would be pretty overkill.
In terms of "other components", the big thing (though it's not a Rails thing) that comes to mind is Test::Unit. While Rails just ships with Test::Unit, and doesn't constrain you from using something else, it's worth mentioning that there are other testing frameworks available. RSpec is the other big player here, and there's also ZenTest. You may also look at Shoulda, which is an add-on, more than an alternative.

How to organize a Rails App

For the first time I'm creating a quite complex Rails app.
I'd like to know what's the best way to organize that app by folders. Until now, I'd do everything under one app (all the models, controllers, etC) but reading some open source code I realize that they put everything under different apps.
Like for example Spree Commerce. They have a general folder and inside that they have different apps (API, core, admin, etc). How is that done and is that the best way to do it?
I'd like to get pointed to the best way to do it (a book, blog, anything) so I can understand how I can architect my app for future maintenance.
thank you
As an aside I think the title of your question is a little confusing. Rails, by using convention over configuration, defines 'how to organise a Rails app'. I think your question is rather about how to architect your application as opposed to anything Rails-specific. Maybe tweak the title?
That aside, without knowing any more detail about your project it's a tricky question to answer, but I'll give it a go.
All applications should start off simple, if you believe (like I do) that you should start by building the simplest thing that could possibly work. Given this, since you're using Rails, then in all likelihood the simplest thing would be to structure your app as a vanilla Rails 3 application. This will probably (I say 'probably' because I don't know any specifics about the app) allow you to get a beta version of your app up and running pretty quickly without worrying about complexities which at this stage in the development of your project are not a problem.
If you need to create an XML or JSON-based API then Rails makes this really easy using the standard framework, which will allow you to spend more time thinking about the API design than how to code it, and it's the API design which is the most important thing to get right in the first instance.
Similarly, your Admin site can be part of the same app just in a different namespace. If you find later down the line that you want it as a separate app, you can do this (maybe you could use the awesome API you designed to facilitate this), but why bother designing it with this added complexity (and hence extended development time) in the first place if you don't have a good reason for doing so?
Once you have your app up and running and people are starting to use it, you start to get a picture of where the bottlenecks are and where the design could be improved. At this stage, if there's a need, you can start to move parts of the app to scalable solutions, such as running your API as a standalone service, introducing caching, changing data stores and other improvements and optimisations.
Even if your app is as wildly successful (and I hope it is!) then re-architecting your application whist continuing to run the existing service is still entirely possible, as Twitter have proved. Just stick to Knuth's statement and you'll be alright.
Regarding reading material, that's a tricky one. For me a lot of the XP and agile development classics taught me a huge amount about how to approach program and app design. I'd also check this StackOverflow topic for book inspiration.
Good luck!
Spree uses Rails' Railties (Rails::Engines). Railties are introduced in Rails 3 to make it more modular and easy to extend. Rails 3 itself is a collection of Railties (ActiveSupport, ActiveModel, ActiveRecord, etc.).
If you are developing a complex app I would suggest spending some time planing its' architecture. Designing a complex app without any initial planning would definitely end with a maintenance nightmare down the road. It also introduces a huge learning curve for the new team members, slow down your new feature introduction and of course, frustration.
Anyway, don't over optimize, but don't forget to design your architecture for your needs.
IMHO, I will create very complex projects as one app. I have reason to believe that Spree and Radiant build under seperate apps so that under the pretense of their open source communities, contributors can contribute code easily without tampering with the core data, and the core workings of the application.
Otherwise, you should be alright just building it as one app. Just keep it neat.
Here is what have kept me sane for several years of RoR development:
I use Rails Engines, but keep them in same codebase as the main app. Here is good starter for modular Rails app:
https://github.com/shageman/the_next_big_thing
Wherever I can I try to reduce coupling and use composition to make things easily testable, reusable and maintainable. This helps to eventually extract module or engine as separate gem. Composition is done by routes (mounting), directory overlaying (assets), dependency injection or configuration.
If I don't need to re-use an engine I put it in the same code base as the main app which is single deployment unit. Thanks to that I don't need to switch between projects in my IDE. While in development environment any changes to the engine code are instantly picked up by Rails reload mechanism.

Sinatra vs. Rails

I've worked through some of the Sinatra and Rails samples, but I'm having a hard time figuring out which features belong to which technology.
What specifically do I gain by using Sinatra/Rails? Is it just ActionPack/ActionView? Correct me if I'm wrong, but I COULD just use Webrick/Mongrel and serve up my .erb files right? And I could use ActiveRecord technology in those files and still access post variables, session state and querystring variables right?
So, what I'm asking you guys is, if I start with the PHP-like scenario above; Webrick + ERB + ActiveRecord, what do I gain by using Sinatra? And what do I further gain by using Rails?
For Sinatra, it's really almost like a wrapper around Rack. So you first need to ask what the point of Rack is. Rack is basically a specification for how a framework should return a result, it can use what's returned with any web server that Rack supports. So it's really a compatibility layer that allows you to choose your framework/server combination at will, without worrying about whether they'll work together. If your framework is Rack-compliant, you should be able to deploy on practically any server via Rack.
Now, the thing is Rack is very low level. Frameworks such as Sinatra give you things like nice routing, helpers, before/after filters, and a lot more. You just need to look to the docs to see what you can get. Rails is much more featureful, and in many ways "magical". That is, you might write a single line in Rails that ends up doing quite a lot, which for some is a good thing, and for some too magical. I personally prefer Sinatra for this reason, at least before getting a decent understanding of Rails internals.
The gain by Rails is ActionView/ActionPack. But you can just replace by Mongrel/Erb. It's something different.
It's all herlper you have in your view like name_route or error management in your form. It's all resources management and all plugin like InheritedResources. The advantage of Rails.
There are some tool like the Padrino environment to help you to have all of this helper. But It's really speeder after all plugin activate ? I don't think so.
With Rails 3, Rails is a complete Rack application with a lot of RackMiddleware. You can just drop off some middleware to increase your response.
This question is still relevant until today. And with rails' features are increasing over the time, I want to add a new answer.
There are so many gems right now, so what you can achieve in Rails, most likely you can achieve it too in Sinatra. If we want to compare between Rails and Sinatra (or any other frameworks), we just need to compare the performance and the ease of use.
One of Rails doctrine is convention over configuration. When you create a project in Rails, automatically you get many gems included in your Gemfile. Not only gems, when you look at config directory, you'll see many things included. This doctrine is the reason why the magic can happen in the first place. Once you break the convention, you have to modify -or even create- your configuration.
When we want to have more flexibility but still not reinvent the wheel, we can use framework like Sinatra, where only not so many features is enabled when we first create the project. Even so, I've created mini rails from Sinatra: I just adopting rails' way, with libs/gems that I really need. Because I need to develop my own configuration, the development time was longer than using rails.
If you see this web frameworks benchmark, you'll see that Rails is so slow while other ruby framework, like Sinatra, can be found much higher than Rails.
So, when the best to use Rails?
You need fast development time. Just follow the convention;
The future features of your apps are still unknown.
When the best to use Sinatra?
You don't need fast development time;
Sinatra can be fast if you only work in mini project;
You know that you won't add many features in the future.
What do you gain from Rails? Development speed.
What do you gain from Sinatra? Flexibility.

Resources