Install Rhodes

Macintosh

If you’re running Macintosh, download the latest RhoStudio for Macintosh. This contains the Ruby stack, Redis, RhoConnect and Rhodes.

Click on the RhoStudioInstaller .dmg download file to open it. You will get a window similar to this:

Rhostudio-mac-install
Run the install gems script (double-click on install gems). A terminal window will open; wait for the
gems install process to complete.
Then drag RhoStudio to the Applications folder.

Windows

If you’re running Windows, download the latest RhoStudio for Windows. This installs the Ruby stack, Redis, RhoConnect and Rhodes.
Once the installer has completed, and you have installed the Java Development Kit, you can skip
to the Setup Rhodes section.

Java Development Kit

You need to have the Java Development Kit (JDK) installed.
If you are planning to build for Blackberry or Android, make sure you have JDK version 1.6.0_2 or
higher installed. The recommended version is 6.0 update 11.
For Macintosh, JDK version 1.6.0_24 for Mac OSX 10.6 is available here. Install it and then run
“Java Preferences” utility to change default version.
The Sun JDK for Windows or Linux is available here. The 32-bit Windows version of the JDK is
required for Blackberry tools.
You will want to have your JAVA_HOME variable set; have JAVA_HOME/bin set on your path.

Rhodes Gem

To install the Rhodes gem, you will need the following tools installed:

  • Ruby (On Windows, RubyInstaller is a convenient way to install Ruby)
  • RubyGems (RubyGems offers a .tgz, a .zip, and a .gem download. You want the .zip.)

Windows doesn't come with the necessary build tools to install gems ('make', for
example). There are various ways to get these tools, but the GnuWin32 project at
http://gnuwin32.sourceforge.net/ provides the tools, and can be conveniently installed
via the GetGnuWin32 installer at http://sourceforge.net/projects/getgnuwin32/files/.>

The first step in using Rhodes is to install the Rhodes gem (you may want to put “sudo” in the front of this command on OS X):

$ gem install rhodes

If you get any `no such file to load -- something` messages while running the rake tasks
or rhodes commands, this can usually be resolved by putting "sudo" in front of the
command, as in `sudo gem install something`.

Setup Rhodes

Once you have Rhodes, you will need the SDKs for the platform you want to build your app on.
These instructions are found
here.

After you install the gem and your desired SDKs, you need to run:

$ rhodes-setup

 

This will prompt you for where you installed the SDKs for the various platforms. The installation
script will display its best guess as to where the SDK is. You can then enter a new location, or
leave it blank to use the suggestion. If you are not building for a specific platform (for example, you
can’t build for the iPhone on Windows), you can leave that SDK location blank. You can find
prerequisites for each platform here.

Source : http://docs.rhomobile.com/rhodes/install#rhodes-gem

Beginner’s Guide To Ruby On Rails

Get Rolling

To get your feet wet with Rails, it’s best to simply install it on your own machine and start playing around. This requires just a few steps.

On Windows do the following:

  1. Install Ruby 1.8.6 using the one-click installer from www.ruby-lang.org. Make sure to select “Enable Rubygems” during installation. It’s probably a good idea to install ruby as admin.
  2. Update Rubygems. Rubygems is Ruby’s package management system, and Rails needs a newer version than the one that ships with the installer. To do this, execute gem update --system in the console as admin. Next, you’ll need to add the GitHub gem server to Rubygems with gem sources -a http://gems.github.com
  3. Install Rails and its dependencies with gem install rails and gem install mysql. (You can use other databases, but MySQL is the easiest to set up.)
  4. Install the MySQL Database from mysql.com. If you’ve done Web development before, you probably already have it on your machine.
  5. Create a Rails application. Enter rails -d mysql <appname>. “Appname” will be the name of the sub-directory your app is created in.
  6. Go into the created application’s directory and execute ruby script/server. Point your browser to localhost:3000. You should see the Rails welcome page. Follow its instructions.

To edit Ruby code, you can use any text editor. If you just have to have a fancy IDE, try NetBeans. I recommend Notepad++, a great, lightweight freeware editor.

On a Mac, you’re lucky. Mac OS 10.5 comes with Ruby, Rails and SqLite3. You just need to update your packages by issuing a few commands:

1 sudo gem install rubygems-update
2 sudo update_rubygems
3  
4 gem install rails
5 gem install mongrel

If you need more detailed help on installing Rails on 10.4 Tiger, check out the tutorial on the Rails wiki or in this blog post. Now you can create your app with rails <appname>.

On Linux, the installation depends on your distribution.

A Bird’s Eye View Of Rails’ Inner Workings

This is the part I find missing in most other tutorials about any topic. I want to present an overview of the most important components of Ruby on Rails to help you understand how they work together to process requests. I will be more detailed in the controller section because that’s the most important one, and if I left things out there I wouldn’t be able to paint the whole picture.

Controller

When the request hits your server running the Rails app, the first component handling it is the ActionController.

The ActionController and all of its parts correspond to the controller-part of the MVC stack. Before actually handling the request, the ActionController inspects it to determine which of the controllers in your application is responsible for the request.

These lookups are called routes and are defined in config/routes.rb. If you take a look in that file, you’ll see lines similar to these:

1 ActionController::Routing::Routes.draw do |map|
2   map.resources :users
3   map.connect ':controller/:action/:id'
4 end

The details of route definition could fill an article of their own. If you’re interested in its precise workings, take a look at the ActionController::Routing documentation in the Rails API.

Simplified, two kind of routes appear here. The last one is the traditional style of defining routes. These are formed like simple regular expressions, with the :foo part being a placeholder.

If a request’s URL matches one of these expressions, its parts are mapped to the placeholders. These are then examined to determine the correct controller, the action within the controller and further parameters like id (id always contains the id of the object that the client wants to work with). For example, a URL like /foo/bar/123 would be mapped to the FooController; the bar action and the value of params[:id] would be 123.

The first line is a shortcut to create a large number of those routes in one sweep. Routes created this way adhere to the REST principles. Again, this is a topic large enough to warrant its own article. For the sake of this introduction, let me just illustrate the effect of map.resources :users as an example. If you put such a line in your routes.rb you’re telling Rails that you want users to be a resource. That means seven routes are installed that all point to the UserController.
These seven routes match not only against the URL of the request but also the HTTP method. The mappings are:

1 GET      /users            # will point to the index action
2 GET      /users/new        # will point to the new action
3 POST     /users            # will point to the create action
4 GET      /users/:id        # will point to the show action
5 GET      /users/:id/edit   # will point to the edit action
6 PUT      /users/:id        # will point to the update action
7 DELETE   /users/:id        # will point to the destroy action

All of these actions of the UserController are expected to behave in certain ways.

  • The index action should display a list of all existing users.
  • The new action should display a form for the creation of a new user that is submitted to /users via POST.
  • The create action should take the form’s input and create a new user in the database.
  • The show action should display the user with the corresponding id.
  • The edit action should display a form for editing the user. The form should submit to /users/:id/ via PUT.
  • The update action receives the form data and updates the user in the database.
  • The destroy action deletes the user from the database.

Because PUT and DELETE aren’t supported by all browsers, forms that are supposed to use these methods submit via POST and tell the server their intended method via a hidden form field named _method.

Once controller, action and parameters are determined, the action can be called. But before that actually happens, Rails inspects the filter chain for the action to see if there are any filters to be executed before the action runs. Such filters are incredibly useful for things like user authentication. To ensure that only logged-in users of your application can access certain actions, you would define a filter that checks the session for valid credentials. Such a filter could look like this:

01 class UserController < ApplicationController
02  
03   # Require valid login to access the update action
04   before_filter(:require_login, :only => :update)
05  
06   # Lots of actions defined here
07   # ...
08   # ...
09  
10 private
11  
12   def require_login
13     render(:text => "Unauthorized", :status => 401) unless session[:user_valid]
14   end
15  
16 end

Let’s analyze this example line by line. The UserController inherits from the ApplicationController. All of your controllers should. The ApplicationController can then contain code that should be shared among all the controllers in your application. You could, for example, put the require_login filter in there to require a valid log-in for all your controllers.

The next line declares a before filter. By making the declaration using the symbol :require_login, you’re telling Rails to use the require_login method as a filter. This alone would apply the filter to all actions
in the UserController. The additional parameter :only => :update tells Rails to use the filter only when the client wants to access the update action. In a real controller, this line would be followed by the definitions of all the actions your controller contains. In this example, they’re omitted for brevity.

The keyword private marks all the methods defined afterward as private to the UserController. This implies that they can’t be used as actions. We don’t want require_login to be used as an action, so we’re putting it here.

Require_login checks if the field :user_valid in the session is present. This is, of course, a pretty drastic simplification of a real authentication scheme, but it’s sufficient for the sake of illustrating filters. Unless a user is logged in, the filter renders a simple error message.

Now, here’s a detail you need to know to understand this. Rails works through all the filters applying to an action and only aborts request processing for three reasons:

  1. A filter raises an Error.
  2. A filter returns false.
  3. A filter renders somethings or redirects.

So, this single line is all that is needed to protect our sensitive actions against malicious clients. Again, I’m simplifying this a bit. To make an application really secure, you will of course need a little bit more code to properly maintain session state. To find out more about filters, read the ActionController::Filters::ClassMethods documentation in the Rails API.

Let’s see how Rails continues with the processing of the request.

After the client’s request has passed all filters, the action finally executes. Let’s run with our example from the filters section and assume the client wants to execute the update action after editing the user in a from provided by the edit action. Both actions could be defined like this:

01 def edit
02   @user = User.find(params[:id])
03 end
04  
05 def update
06   @user = User.find(params[:id])
07   if @user.update_attributes(params[:user])
08     redirect_to users_url
09   else
10     render :action => :edit
11   end
12 end

Let’s work through this line by line again. First, note that actions are defined as simple parameter-less methods on the controller. Their input and output is realized a little differently from what you’d expect from a method. Actions retrieve all the information they need to process the request from their controller through a few accessors, mainly params and session. There are more (cookies, request), but they’re not used nearly as often as these two, and I don’t want to complicate matters more than is necessary here.

The params method returns all the parameters of a request. These usually result from its querystrings or the postbody, but can also be created from JSON or XML data structures. Through routes, parts of the URL can also become parameters. This is where the :id parameter in the example is read from. If the client requests /users/123/edit/ and we have a route definition map.resources :users, then 123 becomes the :id parameter for the edit action, because the route definition generates (among others) a route that looks like this:

1 map.route '/users/:id/edit',
2           :controller => 'users',
3           :action     => 'edit',
4           :method     => :get
5  
6 <!-- The "session" method can be used to access data in the session. Whatever you put in here will be available in subsequent actions in the same session. This is commonly used to store log-in information or things like shopping cart contents. -->

For output, an action basically has two options. It can either redirect the user or render a template. The templates for a Rails application are organized the same way the controllers are. They reside in app/templates/<controllername>/<action>.html.erb, and if no output is specified in the action, Rails renders the template belonging to that action by default. That’s why you don’t see any output code in the edit action. The only line in edit pulls the user we want to edit out of the database and puts it into an instance variable of the controller to make it available to the template.

The update action begins with the same statement, again fetching the user form the database. In its next step, the user’s attributes are updated with the data that the action received from the client-side form. The update returns true on success. In this case, the client is redirected to the list of users.

This redirection deserves closer inspection. The redirect_to command takes a URL, but instead of hard-coding these URLs (/users in this case), it is conventional to use URL helpers like users_url. The helpers are generated automatically by the route or resource definitions.

If updating the user’s attributes does not succeed, two things happen inside the update_attributes call. First the user’s errors property will be filled with details on why the update didn’t succeed, and the call will return false instead of true. As a result, the client is not redirected; instead, render is called, with :action => :edit as its parameter. This tells render to render the template belonging to the edit action of the current controller.

Why not redirect to the edit action, you may ask? We could do that, but we’d lose all the edits we made to the user and lose information on the errors that occurred. When the edit-template is rendered instead during the processing of the update action, the user that failed to update is still in memory with all its pending edits and the errors. We can use this data in the template to pre-fill the form with the values we just entered (but didn’t save to the database) and provide information to the client on what went wrong.

There’s one last important thing to note here about render and redirect_to. It is not apparent from these examples, but calling render or redirect_to does not stop the processing of the action. These are both just methods and not special control flow statements. So, when render is called, the template isn’t rendered yet; rather, the controller renders the template after the action has processed. Any statements following a render are still executed.

Model

The second important part of MVC in Rails is the Model. Its role is played by the ActiveRecord module, an implementation of the pattern of the same name. ActiveRecord::Base functions as a base class for the models in your application. If you derive your models from this class, you’ll have them automatically linked to tables in your database and can very easily load, edit, save, create, delete or list them. Mappings between the structure and behavior of your models and the tables in the database are fully automated mostly, provided that you adhere to a few rules in the design of your tables. The general principles are:

  1. Your table name is the pluralized, underscored variant of your classname. So, a class User would be mapped to the table users.CookieRecipe would be mapped to cookie_recipes.
  2. Your table needs to have its primary key on an integer column called id with the auto increment property.
  3. Associations to other tables are stored in columns that are named after them. If you want to store posts belonging to a user, the posts table would need a user_id column

If you have a table and class that are connected via their name, like users and User, any column in the table is available on the model as a property. If you want to create a User, you’d just instantiate an object in Rails:

1 u = User.new

Then you can begin setting its properties:

1 u.name = "Michael"
2 u.age  = 35

You could also provide these settings upon creation:

1 u = User.new(:name => "Michael", :age => 35)

To store the new user in the database, tell it to save:

You can find records in a lot of ways:

1 u = User.find(123)               # finds the user with id 123
2 u = User.find(:all)              # returns an array containing all users
3 u = User.find_by_name("Michael") # a "magic" finder

I don’t want to go into the details of all of these options. You can find them all in the ActiveRecord::Base module documentation in the Rails API. I’d rather introduce two important features of ActiveRecord: associations and validations.

I have already mentioned associations briefly and given an example of posts belonging to users. How would you actually implement that? Well, as mentioned, you first put a user_id column in the posts table to link the two tables. Then you need to make your models aware of the link (unfortunately, it doesn’t do that automatically). But don’t worry, you only need two lines of code for that:

1 class User < ActiveRecord::Base
2   has_many :posts
3 end
4  
5 class Post < ActiveRecord::Base
6   belongs_to :user
7 end

That’s it. These two lines make helpers available in both models that allow for navigating the models. Given a post, you could access its user via post.user or get all posts of a user by saying user.posts.

Validations are constraints that you can define in your model to ensure that the model is only saved to the database if those constraints are met. Rails provides a lot of predefined validations that ensure that a property isn’t empty, is within a certain numeric range or matches a regular expression. But you can basically use anything you can write down in code as a validation. Say you want to ensure that your posts have titles not longer than 100 characters and that the post body is always present. You would extend your Post class like this:

1 class Post < ActiveRecord::Base
2   belongs_to :user
3  
4   validates_presence_of :body
5   validates_length_of   :title, :maximum => 100
6 end

A call to the save method on a post that doesn’t comply with these restrictions will return false, and the post will not be saved to the database. You can then examine the post’s errors object by accessing post.errors and communicate to the users what went wrong. The Rails-provided validations all come with descriptive error messages that you could retrieve with post.errors.full_messages, for example.

ActiveRecord has a lot more depth and functionality than presented here. Even complex models and their relations can be handled pretty comfortably. But presenting all this exceeds the scope of this article. The API doesn’t help much if you want to explore all these possibilities; so, to get a deeper introduction, I recommend the Rails Envy ActiveRecord tutorial.

View

We’re almost at the end of our overview. The last missing part is MVC’s V, the View. All the components related to this are aggregated under the ActionView module. At the core of Rails’ views are the ERB templates, but they are backed by a large library of helpers that can be used to generate forms, URLs, sub-templates and other little tools that can make your life easier.

In the controller example, I talked about how the render method is used to render a template. An action that doesn’t explicitly render or redirect automatically renders its corresponding template in app/templates/<controller>/<action>.html.erb. The file extension .erb stands for “Embedded Ruby,” and that’s what the templates are: HTML files that are dynamically filled with content through the use of special script tags that contain Ruby code. These special tags work very similar to the ones PHP uses. Let’s take a look at an example:

01 <html>
02   <head>
03     <title><%= @pagetitle %></title>
04   </head>
05   <body>
06     <h1>Post: <%= h @post.title %></h1>
07     <p>Written on <%= @post.date %></p>
08  
09     <div id="postcontent">
10       <%= h @post.content %>
11     </div>
12  
13     <% if @post.user.posts.count > 1 %>
14       <p>Other posts by <%= @post.user.name %>:</p>
15       <ul>
16         <% @post.user.posts.each do |post| %>
17           <li><%= h post.title %></li>
18         <% end %>
19       </ul>
20     <% end %>
21   </body>
22 </html>

Tags beginning with <%= evaluate the expression they contain and insert them into the document. The little h you see sometimes is a helper function provided by ActionView that escapes characters that are not valid HTML. You should always use this if you’re displaying user-entered content to prevent cross-site scripting attacks.

Below the postcontent div, you can see another type of erb tag, without the equals sign. This means that its content is executed but not inserted into the document. We’re opening a conditional statement here. Everything between the if and the end will only be executed if the current post’s user has other posts. This affects both Ruby and HTML code.

The next tag is also pretty interesting and different from the ones used before. We’re combining the power of Ruby blocks here with ERB to iterate over a user’s posts. The each method executes its block for each of the members of a collection and makes the current member available to the block. I’ve called the block’s parameter post here, so we can refer to the current post under this name within the block. In ERB, you can put HTML within blocks just as if it were code.

You’ll notice that I’m using two instance variables in this template, @pagetitle and @post. They are the main means of passing data from the controller to the template. Instance variables that exist in the controller can also be accessed in the template. It’s that simple.

From the content of the page, you can see that we’re probably rendering the show action of a post‘s resource here. The controller action to feed this template with data could look like this:

1 def show
2   @post = Post.find(params[:id)
3 end

The @pagetitle could be the result of a before filter:

1 before_filter :set_title
2 def set_title
3   @pagetitle = "Showing Post #{params[:id]}"
4 end

Rails’ templates can harness the full power of the Ruby language and have access to the full stack right down to the models. This power can easily be misused to put controller logic or model operations into the templates. But you’re only hurting yourself (and your colleagues) if you do that. You should only put code in the templates that is directly related to displaying data.

As with ActiveRecord, this only scratches the surface of what’s possible with ActionView. Three of the most useful features not introduced here are:

  • Layouts that can be nested so that you don’t have to repeat identical structures in your templates over and over.
  • Partials, small template snippets that can be used to render collections and inserted into other templates
  • Generation of JSON and XML to create Web services, AJAX interfaces and RSS feeds.

To go deeper into the topic, check out the Layouts and Rendering in Rails guide on Rails Guides.

Learning From Rails

Rails takes Ruby’s aim of increasing programmer productivity and happiness and applies it to Web frameworks. Its debut was a truly revelatory experience because it showed developers that that power doesn’t have to come with the clumsiness that other frameworks exhibited at the time.

Today, the ideas of Rails can be found in many imitators in other languages, but if you’re not tied to any one of them, Ruby on Rails is definitely worth checking out. You’ll rediscover the fun in programming, and even if you don’t stick with Rails, you definitely won’t regret the learning experience.

The greatest thing about Rails, however, is how it can change your perception of programming in general once you understand its design and the reasons behind it.

First, simply using Ruby — a language that’s quite different from ones you’ve used before, yet similar enough not to be totally alienating — opens up your mind to new ways of thinking and new ways of perceiving programming languages. You’ll suddenly begin to question things you’ve taken for granted. You’ll frown at first on the prospect of opening up and redefining core classes at runtime, but once you’ve done it and seen that your program still runs and looks nicer than before, you’ll appreciate the flexibility and also become a more responsible programmer. You’ll curse every semicolon and every empty pair of braces that other languages force upon you.

For many programmers, Ruby even paved the way to radically different territory, namely functional programming. Ruby is an imperative language, but its treatment of code blocks as objects equal to Strings, Numbers or any other class and its support of closures will slowly prepare your mind for languages like Lisp, Haskell and OCaml, where passing around functions is the predominant way of writing programs. You’ll have a much broader palette of solutions for the problems you’re tackling each day, and those problems will stop looking like all nails.

Rails very much builds upon these wisdoms and makes much use of meta-programming (class rewriting) and functional programming principles. In this way, Rails becomes more than a framework, and becomes rather a domain-specific language for writing Web applications. The exploitation of Ruby’s dynamic features enables a brevity in Rails’ API that does not obscure your code’s intention. After using Rails for a while, you’ll start to develop your own programs in this way.

Rails encourages strict separation of code between your models, controllers and views. Once you’ve written an app in this straightjacket, you’ll begin to see its tremendous benefits. You will develop a sharper eye for the correct location of code. Things you’ve put in your controllers in the past will take their place in the models, and your design will become more fluent, cleaner and more flexible, especially if you let Rails encourage you to thoroughly test your app.

Even if your flirtation with Rails doesn’t turn into a long-term relationship, you’ll gain invaluable experiences that will improve your style in whatever you develop in future.

Further resources

In the hope that your interest has now been piqued and you have an idea of what to expect, I’d like to point you to some resources that will really teach you how to write Web application in Rails.

Further, I’ll point you to some important sources of news, because despite its maturity, Rails is moving at blazing speeds. Don’t misunderstand me: you won’t have to study new features each week to keep up with programming in Rails, but by monitoring the right news sources, you’ll learn invaluable tips and tricks that you won’t find in the tutorials.

First of all, there are books. The advantage of computer books is that they’re usually comprehensive and professionally edited. The disadvantage is that most of them are outdated by the day they hit the shelves. So, the only books you should really bother reading are the ones that are just out. Fortunately, the standard Rails manual, “Agile Web Development with Rails” is just receiving the finishing touches for its third edition, which will cover the most recent changes in the framework. It’s good for beginners and doesn’t go very deep, but that’s okay. If you want to go deep, you can just read blog articles about the subjects you’re interested in after you’re done with the book.

To learn Ruby, you could try Programming Ruby (the “Pickaxe”), the guide written by the Pragmatic Programmers that first brought Ruby to the west. Its first edition is even free and can be found at ruby-doc.org alongside the official Ruby API. The second (and upcoming third) edition is definitely worth the money, though, especially for its chapter about the inner details of Ruby’s object and method dispatch system.

People who don’t like the Pickaxe usually recommend Hal Fulton’s “The Ruby Way,” which teaches the language in a more task-oriented way.

If you’re just entering the world of Rails, you’ll also have access to what will probably be a pretty awesome library of documentation (if it isn’t already!). A few months ago, the Rails team launched an effort to provide comprehensive, up-to-date and free information about everything Rails at Rails Guides.

If you’ve taken your first steps, you should subscribe to the official Ruby on Rails blog, mainly for important announcements and its “This Week in Rails” feature, which provides a very convenient overview of the development of Rails.

If you want to keep in touch with the greater Rails eco-system, you should subscribe to the Rails Envy podcast. These guys will point you to nice plug-ins, tips, tricks and important blog posts every week.

You could, of course, just read those blogs yourself, but beware: Rails has a lot going on in it, and I prefer to have the information predigested in some form. However, if you’d like something to chew on during those boring hours at work, check out these blogs:

Should you get stuck in your adventures, Googling often helps because most of the problems that beginners experience are similar, and for almost any hurdle you may encounter, somebody somewhere has already written a blog post about it. If this is not the case with your problem, ask for help on the Ruby on Rails mailing list or the Ruby mailing list. The people in the Ruby community are usually very friendly and helpful.

Source : http://coding.smashingmagazine.com/

Getting Started With Ruby On Rails

The Idea Behind Rails

Ruby on Rails was created by David Heinemeier Hansson as a kind of byproduct of Basecamp’s development at 37signals in 2004. Basecamp was built in Ruby because Hansson found PHP and Java not powerful or flexible enough. It was quite an obscure language back then, without the large eco-system available today. To make development easier, Hansson rolled his own Web development framework, based on simple ideas that had proven successful elsewhere. Rails is founded on pragmatism and established paradigms instead of exotic new ideas. And that’s what made it so successful.

Rails is based on the Model-View-Controller pattern that splits your application into three parts:

  • The Models are your business objects describing the structure and behavior of the problem your application is trying to solve. These are usually backed by an Object-Relational-Mapping framework that persists your objects to a database in the background.
  • The Views are the templates that render data to the user and all the logic surrounding presentational aspects of your app.
  • The Controller sits at the heart of everything, processing requests from clients, initiating changes in the models and triggering the rendering of the templates.

Rails is “opinionated software.” It doesn’t want to be everything for everyone. It focuses on one way of doing things and streamlines all its parts around that way. That’s not to say there’s no possibility of doing things differently if you need to, but you’ll definitely have it easier if you do things “the Rails way.” And that way happened to be exactly the right one not only for Hansson but for a lot of other developers, too, another important reason for Rails’ success.

Programmer productivity was the main goal during Rails’ development, not performance. This has led to a lot of controversy and claims that arise over and over about how Rails can’t scale. This is Rails’ own fault to a certain degree. In its early days, it had the image of a Web development framework messiah of hope and wonder that would lead us all to the promised land were applications wrote themselves. The Rails team didn’t do enough to keep expectations more realistic, and some people became disappointed.

While it’s true that Ruby on Rails is slower than comparable stacks on PHP or Python, it certainly does scale, as hundreds of successful deployments are proving. You’ll just need to scale sooner and put some thought into it. Remember also that Ruby’s current default implementation is terribly inefficient, but alternatives are on the way. There’s nothing inherently slow about the language, though, as blazing-fast implementations of Smalltalk (a language very similar to Ruby) prove. Ruby will only get faster. As the saying goes, you don’t have a performance problem until you have a performance problem, and all this talk should not scare you yet. You haven’t even started. ;)

Now, before I introduce you to the framework, let’s get started with Ruby.

A Gem From Japan

Ruby on Rails owes not only half its name but its entire feel and flexibility to “Ruby,” that neat little language from Japan.

Ruby came out in 1995 and was developed by Yukihiro Matsumoto, or “Matz” as he’s called in the community. Version 1.0 was released in 1999 and slowly gained recognition in the west from then on.

A key point in the spread of Ruby was the release of “Programming Ruby,” also called the “Pickaxe” (a reference to its cover illustration), by the Pragmatic Programmers. “Programming Ruby” was the first comprehensive English guide to the language and API.

Ruby was designed with simple principles in mind. Matz took the most successful and powerful elements from his favorite programming languages — Perl, Smalltak and Lisp — and combined them into one language with easy syntax. One goal was to make Ruby feel “natural, not simple” and to create a language “that was more powerful than Perl, and more object-oriented than Python.” This results in Ruby’s core principle: Everything is an object.

Objects

Let’s stop here and examine this. Really, everything is an object in Ruby. True and false are objects, literals are objects, classes are objects. You can call a method on a numeric literal:

1 >> 5.next
2 => 6

Operators in Ruby are nothing but methods:

1 >> 5 * 10
2 => 50
3 >> 5.*(10# times-operator called as a method (dot-notation)
4 => 50       # with a parameter (in parentheses)

Ruby is extremely flexible and open. Almost everything about it can be changed or manipulated at runtime:

  • You can add and remove methods and variables to and from objects.
  • You can add and remove methods and variables to and from classes.
  • You can truly manipulate any class this way, even core classes like String and Integer!

Here’s an example:

01 >> "hi".repeat(4)
02 NoMethodError: undefined method `repeat' for "hi":String
03 >> class String     # Open the string class and add the method
04 >>   def repeat(i)
05 >>     self * i
06 >>   end
07 >> end
08 => nil
09 >> "hi".repeat(4)   # Call it again on a fresh String literal
10 => "hihihihi"       # And there it is!

Here, I defined the method repeat on the String core class, and it was immediately available on a string literal.

And he who giveth, taketh away:

1 >> class String             # Open up the method again
2 >>   undef_method :repeat   # And remove the method
3 >> end
4 => String
5 >> "hi".repeat(4)           # Try to call it
6 NoMethodError: undefined method `repeat' for "hi":String

I could have also done this with predefined methods. They are no more “special” than the methods we have defined.

Let’s review the definition of repeat in the above example for some more interesting tidbits. Note that we’re not saying return anywhere in the body. That is because in Ruby, methods always implicitly return the value of their last expression. You could of course always jump out of a method by using return before reaching the last statement, but you don’t have to. The expression we’re returning is self * i. Self is equal to this in Java and $this in PHP and always refers to the current object. The times-operator on a string repeats the string as often as told by the second operand/parameter, i in this case.

Loops

You rarely see manual iterations in Ruby, like for or while loops. Instead, Collections come with their own iterators that you can pass blocks to, which are executed for every element in the collection:

1 a = "Hey "
2 [1, 2, 3].each do |num|
3     puts a * num
4 end
5  
6 # Outputs:
7 # Hey
8 # Hey Hey
9 # Hey Hey Hey

What you see here is an array literal containing numbers. On that array, the each method is called, an iterator that takes a block and calls the block for every element in the array. The block starts with the do, followed by a list of its parameters enclosed in pipe symbols. Here we have one parameter called num that will take on the value of the array element in each iteration. Inside the block, we’re simply outputting the result of a * num. The definition of * on Strings is to repeat the string accordingly. We could have put the String inside the Block, but I wanted to demonstrate that blocks have access to their surrounding scope.

Syntax

Ruby likes to keep the syntax clean and friendly. You can see this in the above examples. Although heavily influenced by Perl, Ruby doesn’t have Perl’s excessive use of special characters. You can use semicolons to end lines, but you don’t have to (and no Ruby programmer does). You don’t need to surround method parameters with braces in unambiguous situations (although it is recommended you do so if they enhance readability), and you especially don’t need to provide empty braces around an empty parameter list. That’s what makes accessors look so much like native properties.

Blocks are framed by do and end. You should only use equivalent curly braces if your blocks don’t span several lines. The only significant use of special characters is found at variable declaration. Variables in Ruby are prefixed with special characters to indicate their scope. Variables starting with a lowercase letter are local variables. Variables starting with an uppercase letter are constants. (This means that all classes are constants, too, since classes start with uppercase letters.) Instance variables start with an @. Class variables that are shared among all instances of a class start with @@. Finally, global variables all start with a $.

You’ll often find methods ending in ? or !. These are not special characters. It is merely conventional in Ruby to use question marks for methods that query an object for a Boolean condition, like Array#empty?, or exclamation marks for methods that are destructible:

01 >> a = [5, 1, 9, 2, 7]   # Create an array and store it in a
02 => [5, 1, 9, 2, 7]
03 >> a.sort                # sort merely returns a new, sorted array
04 => [1, 2, 5, 7, 9]
05 >> a
06 => [5, 1, 9, 2, 7]       # a still is in its original order
07 >> a.sort!               # sort! instead sorts the original array
08 => [1, 2, 5, 7, 9]
09 >> a
10 => [1, 2, 5, 7, 9]       # a was changed

Conditionals

Conditionals in Ruby are very similar to other programming languages, with two notable exceptions. First, it’s possible to put a conditional after the statement it protects to make the code more readable:

1 execute_dangerous_operation() if user.is_authorized?
2  
3 # is equal to
4  
5 if user.is_authorized?
6   execute_dangerous_operation()
7 end

Secondly, Ruby has not only an if but an unless. This is a syntactic nicety for when you want to check for the absence of a condition in a more readable manner:

1 unless user.is_admin?
2   user.delete
3 else
4   raise "Can't delete admins"
5 end

Symbols

Sometimes you’ll see names starting with a : (colon). These are a very special feature of Ruby called symbols. Symbols can be used to index hashes or mark states in a variable like you would with an ENUM in C. They are very similar to Strings but also very different. The point about symbols is that they don’t really occupy space in memory, and the same symbol literal always resolves to the exact same symbol:

1 >> "a".object_id  # object_id returns Ruby's internal identifier for an object
2 => 3477510
3 >> "a".object_id
4 => 3475550        # a new object on the heap
5 >> :a.object_id
6 => 184178
7 >> :a.object_id
8 => 184178         # the same literal refers to the exact same Symbol object

You’ll find them very often as parameters to methods, where they indicate how a method should work,

1 User.find(:all)   #find all users
2 User.find(:first) #find the first user

or as pointers to methods and variables (see the undef_method example in the “Objects” paragraph above).

Classes and Modules

Ruby supports single inheritance only, but for added flexibility it supports a feature called Mixins. In Ruby, it’s possible to define Modules that contain Methods and constants and to include these modules in a class via the include method. This way, you can extend the functionality of a class very easily.

Many of Ruby’s core classes even use this mechanism.Array and Hash, for example, both include the Enumerable module to provide a lot of convenience methods for iterating over their contents.

Often, Modules pose certain requirements to classes that include them. The Enumerable Module, for example, requires classes to provide at least an each method and an implementation of <=>, too, if its sorting features are to be used.

Modules also serve other purposes. Most importantly, they can be used to organize code into namespaces. Because classes are constants (which means you can’t assign another class to the same name), they can be stored in modules. These modules can then be nested to form namespaces.

These paragraphs probably won’t enable you to write Ruby programs, but you should be able to understand the code samples in this article now. If you want to explore Ruby a little, try the great interactive tutorial at Try Ruby, or take a peek at one of the books listed at the end of this article. If you just want to see some more code samples, check out the Wikipedia page on Ruby.

In the second part of this tutorial we will get rolling with Ruby on Rails, install the engine, take a closer look at Rails’ inner workings and discover main advantages of Ruby on Rails. Please stay tuned.

Source : http://coding.smashingmagazine.com/

A Guide To Starting Your Own Rails Engine Gem

Enginex

Jose Valim, a core Rails contributor, has created a tool named Enginex, which scaffolds Rails 3-compatible engine gems. This tool protects you from many of the gotchas that engine gem developers face. It provides basic set-up, including a test Rails application, which you’ll need to get started.

To begin, run the following from the command line in your standard projects directory:

gem install enginexenginex team_page

With this, you will end up with a project in the team_page directory containing the standard Enginex scaffolding.

Set-Up

To set up our gem, we’ll modify a few files. First, our team_page.gemspec and our Gemfile need a little love.

# CURRENT FILE :: team_page.gemspecrequire File.expand_path("../lib/team_page/version", __FILE__)# Provide a simple gemspec so that you can easily use your# Enginex project in your Rails apps through Git.Gem::Specification.new do |s|F  s.name                      = "team_page"  s.version                   = TeamPage::VERSION  s.platform                  = Gem::Platform::RUBY  s.authors                   = [ "Your Name" ]  s.email                     = [ "your@email.com" ]  s.homepage                  = "http://yourwebsite.com"  s.description               = "A simple Rails 3 engine gem that adds a team page to any Rails 3 application."  s.summary                   = "team_page-#{s.version}"  s.rubyforge_project         = "team_page"  s.required_rubygems_version = "> 1.3.6"  s.add_dependency "activesupport" , "~> 3.0.7"  s.add_dependency "rails"         , "~> 3.0.7"  s.files = `git ls-files`.split("\n")  s.executables = `git ls-files`.split("\n").map{|f| f =~ /^bin\/(.*)/ ? $1 : nil}.compact  s.require_path = 'lib'end
# CURRENT FILE :: Gemfilesource "http://rubygems.org"# Specify any dependencies in the gemspecgemspec

This sets up our gemspec to automatically use files we have committed with Git, and any executables we may add in the future, and to use the VERSION constant that we’ll specify in our gem.

Also, by calling gemspec in our Gemfile, running bundle install will load dependencies from our team_page.gemspec, which is the convention.

Next, to turn our gem into a Rails engine, let’s add or modify three files. First, our top-level team page file:

# CURRENT FILE :: lib/team_page.rb# Requiresrequire "active_support/dependencies"module TeamPage  # Our host application root path  # We set this when the engine is initialized  mattr_accessor :app_root  # Yield self on setup for nice config blocks  def self.setup    yield self  endend# Require our enginerequire "team_page/engine"

To use the mattr functions, our ActiveSupport dependencies are required. We also set up a nice way to configure our gem with the self.setup method. The engine is required at the end of our file so that we can be sure that any dependencies are specified first.

Secondly, our version file:

# CURRENT FILE :: lib/team_page/version.rbmodule TeamPage  VERSION = "0.0.1"end

Lastly, our engine file:

# CURRENT FILE :: lib/team_page/engine.rbmodule TeamPage  class Engine < Rails::Engine    initialize "team_page.load_app_instance_data" do |app|      TeamPage.setup do |config|        config.app_root = app.root      end    end    initialize "team_page.load_static_assets" do |app|      app.middleware.use ::ActionDispatch::Static, "#{root}/public"    end  endend

This defines two Rails initialize blocks that clue us into the root directory of our host Rails application, as well as serve up any files in the root public directory of our gem.

Data Model

To add a model in our gem, we first need to specify a migration and a generator class to copy it over to the host Rails application. Although this process will become much more transparent in Rails 3.1, we now need to build some generator classes. A great resource for this can be found over at Nepal on Rails.

First, let’s add our generators class:

# CURRENT FILE :: lib/generators/team_page/team_page_generator.rb# Requiresrequire 'rails/generators'require 'rails/generators/migration'class TeamPageGenerator < Rails::Generators::Base  include Rails::Generators::Migration  def self.source_root    @source_root ||= File.join(File.dirname(__FILE__), 'templates')  end  def self.next_migration_number(dirname)    if ActiveRecord::Base.timestamped_migrations      Time.new.utc.strftime("%Y%m%d%H%M%S")    else      "%.3d" % (current_migration_number(dirname) + 1)    end  end  def create_migration_file    migration_template 'migration.rb', 'db/migrate/create_team_members_table.rb'  endend

Adding this will allow developers to run rails g team_page from within their Rails application and to create the necessary migration file to power our team page.

Next, we’ll put together a sample migration:

# CURRENT FILE :: lib/generators/team_page/templates/migration.rbclass CreateTeamMembers < ActiveRecord::Migration  def self.up    create_table :team_members do |t|      t.string :name      t.string :twitter_url      t.string :bio      t.string :image_url      t.timestamps    end  end  def self.down    drop_table :team_members  endend

Finally, we can create a sample model namespaced to our gem.

# CURRENT FILE :: app/models/team_page/team_member.rbmodule TeamPage  class TeamMember < ActiveRecord::Base    attr_accessible :name , :twitter_url , :bio , :image_url  endend

What we’ve done so far is walked through the steps for bootstrapping a Rails 3 engine gem. It has been configured as an engine, given its own migration generator, and supplied with an ActiveRecord model.

Now, let’s set up our gem with a route, controller and view that any host Rails application can use.

The Route

Rails engines gems, when set up properly, automatically load the config and app directories of our project. This is handy because it enables us to set up our code with exactly the same structure as a full Rails application.

So, to set up our route, create a routes.rb file in the config directory of our project. To have it match on the team route, let’s do the following:

# CURRENT FILE :: config/routes.rbRails.application.routes.draw do  get "team" => "team_page/team#index" , :as => :team_pageend

A bit of pain can be avoided by examining what we’ve done here. First, we’re going to match the /team route from any requests to our host Rails app.

Secondly, we’ve told Rails to send requests to the index route of the namespaced controller that we’re going to create in our engine. Namespacing our controller is best practice because it isolates our engine code from any application that it’s included in.

Lastly, our route is named so that we can use link helpers elsewhere in our application.

The Controller

Our controllers will live in the app directory, just as we’re used to. One caveat is that we’ll want to place them in a team_page directory, just as we did with our model. It simply needs to load all of our team members to be displayed on the page.

# CURRENT FILE :: app/controllers/team_page/team_controller.rbmodule TeamPage  class TeamController < ::ApplicationController    def index      @team_members = TeamMember.all    end  endend

As you can see, we’ve subclassed our top-level ::ApplicationController, which lives in the host Rails application.

The View

To finish off, we need a view to render. By default, it will use the main application layout from our host Rails application, since we didn’t specify a different layout in the controller.

Just as we did with our model and controller, we’ll nest our view in a team_page directory. Because we want to minimize external dependencies, we’ll write our views in ERB instead of something like HAML.

<!-- CURRENT FILE :: app/views/team_page/index.html.erb --><ul class="team-member-list">  <% @team_members.each do |team_member| %>  <li class="team-member">    <span class="team-member-name">      <%= link_to @team_member.name , @team_member.twitter_url %>    </span>    <%= @team_member.bio %>    <%= image_tag @team_member.image_url , :class => "team-member-image" %>  </li>  <% end %></ul>

Getting Started With Tests

Obviously, we haven’t yet written any unit or integration tests here to cover the gem that we created. Completing this exercise will improve your understanding of Rails 3 engine gems. The enginex tool we used automatically creates a test directory for you with a basic Rails application.

Let’s start by making sure our test_helper.rb file is up to snuff.

# CURRENT FILE :: test/test_helper.rb# Configure Rails EnvironmentENV["RAILS_ENV"] = "test"ENV["RAILS_ROOT"] = File.expand_path("../dummy",  __FILE__)require File.expand_path("../dummy/config/environment.rb",  __FILE__)require "rails/test_help"ActionMailer::Base.delivery_method = :testActionMailer::Base.perform_deliveries = trueActionMailer::Base.default_url_options[:host] = "test.com"Rails.backtrace_cleaner.remove_silencers!# Run any available migrationActiveRecord::Migrator.migrate File.expand_path("../dummy/db/migrate/", __FILE__)# Load support filesDir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

One thing to notice, which is unusual for a testing set-up helper, is that we aren’t requiring our local gem code anywhere in the test helper. Because we’re using Bundler, our gem is actually required in the dummy Rails app via our Gemfile at test/dummy/config/application.rb. Other than that, we’re setting up our Rails environment, booting the application and running any available migrations. Here’s a glance at a sample unit test.

# CURRENT FILE :: test/team_page_test.rbrequire 'test_helper'class TeamPageTest < ActiveSupport::TestCase  test "truth" do    assert_kind_of Module, TeamPage  end  test 'setup block yields self' do    TeamPage.setup do |config|      assert_equal TeamPage, config    end  endend

To continue playing around with how engine testing and integration in a Rails app work, head to the test/dummy/ Rails app and boot the server or play in the console. Everything should work in there as well as it would in any other Rails application.

Resources And Tips

Here are a few helpers to make sure you’re on the right track. The following represents what you would expect the directory structure to look like for your engine gem after following the code examples in this article.

## DIRECTORY STRUCTURE#- team_page/  - app/    - controllers/      - team_page/        + team_controller.rb    - models/      - team_page/        + team_member.rb    - views/      - team_page/        + index.html.erb  - config/    + routes.rb  - lib/    - team_page.rb    - generators/      - team_page/        + team_page_generator.rb        - templates/          + migration.rb    - team_page/      + engine.rb      + version.rb  - test/    + team_page_test.rb    + test_helper.rb  + team_page.gemspec  + Gemfile  + Gemfile.lock

Here’s a simple script to load some team members into your database.

## DATA SEED## => Method 1# Copy the code into your application's db/seeds.rb file.## => Method 2# If you would like to run this code in the engine that you are# developing, place it in the seeds file inside of the dummy app# contained in your integration tests.## With either of the above methods, be sure to run the following from# your command line…##     rake db:seed#5.times do |i|  TeamPage::TeamMember.create!( {    :name        => "Team Member #{i}",    :twitter_url => "http://twitter.com/team_member_#{i}",    :bio         => "A really fancy team member!",    :image_url   => "http://bit.ly/muSWki"  } )end

Some External Resources

Conclusion

The goal of this post was to demonstrate how straightforward it is to create a Rails engine packaged as a Ruby gem.

To recap, we’ve boostrapped our gem, added a model and migration generator, set up a route to hit our controller, created a sample view, and wrote some example tests. This process can be used for any engine gem you feel you need, and it can speed up development time and improve the reliability and maintainability of your code bases. The possibilities are endless. What will you build?

Source : http://coding.smashingmagazine.com