Block Comments in Ruby

This is an easy one. How do you comment out a chunk of code? Other programming languages (C++, Java, etc.) have a slash-star style of block comments, like so:


/*
This is a block comment. You can put whatever you want here.
Even ASCII art! For REAL! o[+++]XXXXXXXXXXXX>
*/
// ...

But what about Ruby?

Ruby has two special tags that you use: =begin and =end. So your Ruby comment would look like this:


=begin
This function returns the minimum of A or B.
For example, if A is 3 and B is 7, it'll return 3.
=end
def self.min(a, b)
# ...
end

Yes, yes! It’s easy!

Wait! What’s that, you say? You say it doesn’t work? Well, that’s tragic–and in fact, it happened to me, too. The key is that these tokens cannot be preceded by whitespace. If they are, it won’t work.

What? Ghetto, you say? Well, tough luck, my friend–this is how Ruby deals with block comments. Just use it, OK? It’s easier than commenting out 130+ lines of code one by one. (Or if you have an IDE that does it in one-shot, great, even better!)

And that’s Ruby comment blocks! Simple!

Source : http://www.railsrocket.com/block-comments-in-ruby

The Controversial Eval Function

Today we’re going to discuss one of those highly-controversial hot topics in Ruby (if there can be such a thing as a “hot topic” in programming languages)–the eval function.

What does eval do? Quite simply, you pass in some Ruby code in a string, and it’ll evaluate it. Observe:


eval "puts 2+2" # => 4
eval "'hello world!'.upcase # => HELLO WORLD

Clearly, this is useful stuff–you can pass in arbitrary code, even assemble your strings on the fly for truly complicated code.

But, eval is a dangerous tool–because it can execute arbitrary code. For example, if you have some code like this:


input = # ... read from some form
eval input
# ...

Some clever script kiddie will send the input system 'rm -rf *', you can kiss your application goodbye. And your family photo-collection. And your MP3 collection. And your hard-drive.

Some people brand eval as an “evil,” “insidious,” “destructive” function. Which is true–it has destructive potential. That’s why you need to sanitize your input. Don’t just send it as-is. Don’t risk it.

On the other hand, eval has a lot of tricky uses for things you might not otherwise be able to do. For example, how would you create a generic “shutdown hook” system for your Ruby application? other programming languages have pointers–in .NET, for example, you can accumulate a collection of pointers, and run those. What can you do in Ruby? You can accumulate a collection of strings to eval!


shutdown_hooks = ["Logger.write 'normal termination'", "Logger.close", "DatabaseConnector.close"]

Voila! You can iterate through them and execute them, just like any set of pointers in other languages.

To recap:

  • eval is merely a tool. It can be used, and abused, like any tool.
  • Use eval as necessary, but avoid it if possible.
  • Sanitize your input! Don’t risk it! Script kiddies abound!

In other programming languages, one of the concerns raised with reflection is that it’s a “heavy” process. How does Ruby stack up? If you know, share it in the comments!

Source : http://www.railsrocket.com/the-controversial-eval-function

Looping Backwards in Ruby

It so happens in Ruby that looping forwards is trivial; if you want to print out numbers from one to five, you can do so like this:


(1..5).each do |i|
puts i
end

This will print:

1
2
3
4
5

But how about going backwards? Can you do this?


(5..1).each do |i|
puts i
end

No! This won’t print anything out! Boo!

Edit: The solution is, happily, as easy as:

5.downto(1).do |i|
puts i
end

Props out to Wayne Conrad for mentioning it in the comments! In any case, you can read on to see a discussion of some other solutions to this problem–solutions that will work if you don’t know if you’re going to be counting up or counting down.


Ok, so you might do this, instead:


count = 5
while count > 0
puts count
count -= 1
end

Ok, that’ll work. But what if you have two variables, x and y, and you want to iterate from x and y–except you never know if x is less than y or greater than y? (If x is less than y, you can use the usual (x..y).each do |i|, but if not, what then?)

There are a couple of ways you can tackle this–one is swapping, and the other is using min/max, and we discuss the reverse series method.

Swapping means swapping x and y if x > y, like so:


x = #...
y = #...

if (x > y)
temp = x
x = y
y = temp
end

(x..y).each do #...

This is a great solution. Sometimes, though, it doesn’t work–like in my case, I had an issue where I go from x to y, and then from y to some other value. Swapping just destroys the second part of the process.

Which brings us to solution two–using min/max functions (which, incidentally, don’t come built-in to Ruby). So you would write:


(min(x, y)..max(x, y)).each do #...

And this will iterate properly, without destroying the values of x and y. Of course, you can define min/max as:


def min(a, b)
return b unless a < b
return a
end


def max(a, b)
return b unless a > b
return a
end

And you can use this solution. AND, if you don't know if x is greater than or less than y, then this solution will STILL work! Yay!

BUT! this solution still iterates forward! If that's a problem, you can try solution three, the reverse series. Observe:


steps = y - x
while (steps > 0)
i = y - steps #(y, y-1, y-2 ... x)
# do something for step i
end

This iterates backwards; the value of i is y, then y-1, then y-2, and so on, up to x. (Or, as mentioned before, you can use downto.)

Phew! So that covers a few different ways of iterating backwards; use whatever works for your needs.

Source : http://www.railsrocket.com/looping-backwards-in-ruby

Private Member Variables in Ruby

If you’re new to Ruby, especially if you’re coming from a Rails background, you probably use attr_accessor (if not outright adding columns to the table in Rails) to add member variables to a class. Like so:


class Player
attr_accessor :x, :y
end

What does this mean? It means you can do things like:


p = Player.new
p.x = 2;
p.y += 3;
puts "Player is at (#{p.x}, #{p.y})."

i.e. you get the ability to both read and write to x and y, for FREE–without any additional code. Smooth!

But, if you’re like me, you will probably reach a point where you want to add some member variables, but not make them publically accessible. How do you do it?

The answer is to use the @name convention, like so:


class Player
def initialize(x, y)
@x = x
@y = y
end
end

Unlike the attr_accessor code above, this does NOT allow you to do things like:


p = Player.new(3, 4)
puts "Player is at #{p.x}, #{p.y}" # raises an error: X and Y don't exist

But, as I mentioned, that’s what this is for–creating private member variables.

Also, realize that in Ruby, objects are very dynamic–you can add properties on the fly! We didn’t explicitly “declare” x and y anywhere in our Player class; yet we can access them.

And that, in a nutshell, is private member variables. One last thing to note–you can almost think of attr_accessor :some_thing as equivalent to:


class Whatever
@some_thing = nil
def some_thing
return @some_thing
end
def some_thing=(value)
@some_thing = value
end
end

But of course, all this is free by using attr_accessor. So use it!

Source : www.railsrocket.com

Ruby on Rails, the Best Kept Secret

by Rajinder Yadav

What is this thing Ruby on Rails!

Well if you’re not a hacker, you can be excused for not having heard about Ruby on Rails (RoR). Even if you’ve heard of RoR, you might not understand the excitement surrounding this dynamic and powerful software development tool. For those not entrenched in the world of software development, technical concepts and language can be a barrier to understanding key benefits of a tool or methodology used by software developers. I’ll present the material here so most anyone can understand and talk about the virtues and merits of Ruby on Rails.

When I use the term ‘Hacker’, it’s in the original true sense of the word, someone who enjoys learning and figuring things out by exploring and tinkering. Before we can talk about Ruby on Rails, we need to learn about Ruby.

Ruby the Beautiful

Ask Rubyist and they will all tell you Ruby is a beautiful fun programming language to code in. Ruby is also a powerful dynamic script language, that is primarily run on the server. The term dynamic means that any hacker can extend the Ruby language and become a language designer using meta-programming. This is really powerful, most programming languages are set in stone when they are created by the designer, you cannot alter and extend them like you can with Ruby.

Back around 1995 Ruby made its public debut, its creator Yukihiro Matsumoto, better known as Matz, wanted to create a “fun” language to program in. Ruby took the best ideas from other programming languages at that time (Perl, Smalltalk, Lisp, Ada and Python).

Ruby has excellent regular-expression (regex) support that Perl is best known for. For the non computer science people, regex is a pattern matching text processing language. Effectively it solves the everyday problem of searching and scanning text using “fussy” matching. When you enter a phone number, a credit card number or email at a website, chances are regex is working behind the scene to make sure the format of the input is valid. You may have a need to “scrape” data from a report. For example, you want to get financial data from several accounting reports, or a list of prices and products names from a catalogue, these are all well suited tasks for regex processing.

Likewise Ruby is a true Object-Oriented (OO) language, in Ruby everything is an object. Alright I don’t know what object-oriented means? Please explain! Well object-oriented languages like Ruby  follow the convention that software can be modelled in terms of objects that have properties and behaviours. Objects from the same “class” will share behaviours, called functions or methods. Likewise objects of a given “class” will have the same types of properties. Take for instance a “Person” class that knows how to talk, walk and eat (the methods). Each Person can have a name, age and gender property.  Think of a “class” as a kind of cookie cutter, that is used to create objects in it’s image. Objects can have relationships, ok not like going on a date, but relations in the same sense that a car object will have with a engine object. This just scratches the surface of OO programming, suffice to say OO languages like Ruby can be a more powerful way to model, organize and construct software.

Ruby makes developers more efficient at writing code that is both concise and easy to read. Beside the productivity boost, you also get code that is easy to maintain. Why is this important? Most of the cost associated with software development is spent on the maintenance life-cycle. I don’t have exact figures but it’s close to 80%-90% of total cost.

Speed Vs Productivity, the Trade Off

Since script code like Ruby is interpreted, it needs to runs on a layer above the OS, in a virtual machine. As a result, you sacrifice a little on the speed. However if you’re really power hunger and need speed, it’s really easy to tap into C/C++ code from Ruby. You can do all the heavy lifting inside your compiled C/C++ code module and then pop back into Ruby land, with Ruby you get the best of both worlds, what trade off! On the Ruby compiled front, there is the Rubinius project that takes a Ruby script and produces compiled code that is as fast as native compiled code written in C/C++. For those interested is producing client side software to run on a desktop, this is a project to definitely checkout.

The great thing about coding in Ruby rather than a compiled code environment like C/C++ is that you can run the code right away. With compiled code you have to deal with project management, compiling and linking code, file dependencies, and makefiles. To get up and running with C/C++ code there is a lot of setup work. With Ruby you’re off and running being productive, just write and run. Ruby also has an immediate interactive mode, known as the IRB. It lets you start-up a Ruby language shell where you can prototype and test ideas. It’s also an excellent environment to learn in and try out new Ruby software libraries called Gems. The IRB gives you immediate access to Gems functionality so you can learn how to use them in your code, this adds to your productivity and learning time is reduced.

Ya but what is Ruby on Rails?

Rails is a Web 2.0 development framework, it allows you to create websites much quicker than tradition web coding. Rails is the chainsaw for website building, Rails is developed using the Ruby programming language and it heavily employs meta-programming techniques. It originally was created at 37signals by David Heinemeier Hansson back in 2004, and is the single reason for making the Ruby programming language popular. Before Rails, Ruby was a fringe language back in Japan where Matz was having fun creating a new language for his doctoral program.

Rails use the Model-View-Controller (MVC) design pattern to separate areas of concern, with these domains it is much easier to understand Rails code. If you want to make changes to how a website page will look, you edit the View. If you need to work with the database, you use the Model. Finally if you want to deal with User interaction, you work with the Controller.  Moreover, Rails use convention over configuration, it removes the major cause of frustration dealing with editing configuration files to get some software service working.

Rails makes working with database seem like one is using basic Ruby objects with properties. No ugly complex SQL statements littering your code. With Active Record and Active Model you get the magic of database interaction without the need to specify some database schema or declare database objects with all the fields before you can begin to read, write and update data in the database. You don’t need to create tables, configure a database, don’t even have to write code to connect to the database, it’s seamless and effortless thanks to the power of Rails. Sounds like magic doesn’t it!

As a result, you can easily switch between databases. A site using IBM DB2 as it’s database can be easily modified to use an Open Source solution like PostgreSQL with very little effort. You need to modify the database table “schema”, to add or delete a field, create an index, no problem Rails migration and Rake to the rescue. You write migration tasks in Ruby code not SQL, so you leverage what you already know, then run the task using rake. You don’t even need to write a rake task, the Rails generator takes care of all the grunt tedious boring work, so you can get on with what really matters, building a website.

Unit Testing

Can you imagine having to test your entire website? Having to click and view each website page. Having to enter, modify, delete data maintained on the database, or test file uploads, it would be time consuming and just not feasible or scalable. Rails has a solution for this, it comes with a Unit testing framework, which helps to assure the quality of the code. Unit tests aids in catching software bugs early that results from code changes. The test cases make sure the code is doing that one thinks it should be doing, that is handles errors properly when they occur. Having an automated testing framework is great, breaking changes are discovered immediately not days, weeks or months after the code has been released into the wild. Any true Rails developer will tell you they follow the Test Driven Development (TDD) process, where unit test code is written along with production code. Each new function will have one or more test case before it’s fleshed out. This way, production code will have full coverage when it comes to testing. Both Ruby and Rails themselves come fully unit tested.

Ruby Gems

Ruby on Rails gets really exciting, when you factor in all the Ruby software written and shared by the community as software modules called Gems. You want to create a PDF document, manipulate images, draw charts, there is a Gem out there for each. Since it’s Open Source you will have many hackers using them, with many eyes finding and fixing bugs. This is the true power of open social engineering! End result is better written software with higher quality when compared to someone trying to reinvent the wheel for themselves. With the benefits of these gems, one can easily stitch together ideas and websites much faster.

To round it all up, Ruby on Rails gets you faster to market, encourages good coding practices. Uses conventions which once learned makes it easy for any hacker to understand someone else Rails app. The code is of high quality since it’s been united tested. Ruby lends to clean concise coding making it much easier to maintain and read. Best of all Ruby, Rails and Gems are all free. That’s right, you don’t need to pay some corporation a hefty licensing fee to use it.

Ruby on Rails Best Practices

As I began my studies in RoR recently, just wanted to know about best practices, so I decided to make a compilation of all the articles I will read this and bond =]

Source: http://www.sitepoint.com/10-ruby-on-rails-best-practices/

If you’re new to Ruby on Rails, one of the most daunting aspects is knowing what’s the preferred way of accomplishing a given task. While a lot of techniques and libraries have come and gone as the community’s preferred way of doing something, there are some best practices that remain, and can lead to writing the cleanest, most secure and maintainable Rails code possible.

Listed here today are 10 of the most popular and useful best practices you can use as a Ruby developer.

Fat Model, Skinny Controller

Arguably one of the most important ways to write clear and concise code in Ruby on Rails, the motto “Fat Model, Skinny Controller” refers to how the M and C parts of MVC ideally work together. Namely, any non-response-related logic should go in the model, ideally in a nice, testable method. Meanwhile, the “skinny” controller is simply a nice interface between the view and model.

In practice, this can require a range of different types of refactoring, but it all comes down to one idea: by moving any logic that isn’t about the response (for example, setting a flash message, or choosing whether to redirect or render a view) to the model (instead of the controller), not only have you promoted reuse where possible but you’ve also made it possible to test your code outside of the context of a request.

Let’s look at a simple example. Say you have code like this:

  1. def index
  2.   @published_posts = Post.all :conditions => {['published_at <= ?', Time.now]}
  3.   @unpublished_posts = Post.all :conditions => {['published_at IS NULL OR published_at > ?', Time.now]}
  4. end

You can change it to this:

  1. def index
  2.   @published_posts = Post.all_published
  3.   @unpublished_posts = Post.all_unpublished
  4. end

Then, you can move the logic to your post model, where it might look like this:

  1. def self.all_published
  2.   all :conditions => {['published_at <= ?', Time.now]}
  3. end
  4. def self.all_unpublished
  5.   all :conditions => {['published_at IS NULL OR published_at > ?', Time.now]}
  6. end

With the methods Post.all_published and Post.all_unpublished, we’ve not only made it simpler to test our code, we’ve also made it possible to reuse that same set of conditions in another location. But as we’ll see shortly, even this is still not ideal.

Reusable Scopes and Relations

In the example above, we still weren’t quite at the optimal level. For example, what if we wanted to fetch a single published post? We’d have to duplicate the conditions in another method—which just leads to more and more junk code.

Fortunately, Rails provides a better way—scopes (in older versions of Rails they were called named scopes). Put simply, a scope is a set of constraints on database interactions (such as a condition, limit, or offset) that are chainable and reusable. As a result, I can call MyModel.my_scope.another_scope, orMyModel.my_scope.first, or MyModel.my_scope.all.

So, taking our previous example again, we could rewrite it as follows in Rails 3:

  1. scope :published, lambda { where(‘published_at < = ?’, Time.now) }
  2. scope :unpublished, lambda { where(‘published_at > ?’, Time.now) }

And in Rails 2:

  1. named_scope :published, lambda { {:conditions => ['published_at < = ?', Time.now]} }
  2. named_scope :unpublished, lambda { {:conditions => ['published_at > ?', Time.now]} }

This would then allow us to use Post.published.all and Post.unpublished.all where needed.

Even better, as of Rails 3, Rails now supports relations—essentially, arbitrary scopes that can be used anywhere. For example, Post.where(:title => 'Hello World').first instead of Post.first :conditions => {:title => 'Hello World'}, meaning you now get powerful features such as chaining for arbitrary database calls.

This leads to better constructed code and more reusable queries—you start to think in terms of what a scope or combination of scopes can achieve—in other words, the big picture—rather than just what your one query is. As a bonus, it makes it much nicer to compose very complex queries such as searches by simply adding the relations and scopes you need.

Package Your Code into Gems and Plugins

If you’ve used Ruby on Rails a decent amount, you’ve most likely noticed the wealth of rubygems available to Rails developers. If there is a relatively general problem, it’s highly likely another developer has already solved it.

So, when you write code you think is general enough—which usually just means you’ve written it more than once before in another application, stop and think about how you can extract it into a plugin or gem suitable for a wider range of purposes. This not only pays off the next time you need said functionality, but it also forces you to stop and evaluate your approach to the problem—more often than not, I’ve found that extracting code from an application has led to a simpler design. You also shouldn’t forget that as a developer, releasing open source code can pay off in other ways.

When it comes to using that code next time, as an added bonus it’ll generally be tested already and well explored—resulting in generally better code from the multiple stages of refactoring.

Along the same lines, spend some time looking at open source gems that already solve your problems. If you’re not sure where to start, a GitHub search is usually a good jumping-off point, and Ruby Toolboxcontains a listing of the most popular plugins in the community.

Use the Built-in Ruby Duck Typing Methods

As a language, Ruby uses several conventions that can make development easier. For example, implementing a to_s instance method on an object will give you a standard way of getting a string representation of your object.

By implementing these standard type conversions—in addition to to_s, there’s also to_i for integers andto_a for arrays—you make it possible for your Ruby code to be more concise. As an example, have a look at the following string interpolation:

  1. “Hello there, #{user.name}”

If you alias the name attribute to to_s, you could instead write simply:

  1. “Hello there, #{user}”

Other places in Ruby that use to_s (and, for other situations, to_i and the like) will automatically take advantage of this string representation of your object.

Alongside this, you can also implement the Enumerable module for any of your classes that you want to provide with useful iteration features. All you need to write in your class are the each and <=> methods. These two simple additions give you a whole heap of extra functionality for free: methods like mapinject,sortmaxmin, and a number of others.

Manage Attribute Access

By default, when using mass assignment in Rails—that is, code similar to User.new(params[:user]) and@user.update_attributes params[:user]—Rails will assign every attribute without doing any checking. Your validations prevent bad data but they don’t, for example, prevent you from overwriting an attribute that you don’t want to change.

To solve this, ActiveRecord uses two methods—attr_protected and attr_accessibile. Usingattr_protected, you declare a blacklist of variables you don’t want assigned (for instance,attr_protected :admin, :password_hash). Using attr_accessible, which is generally prefered, you declare the ones you do want to be able to assign (for instance, attr_accessible :login, :email, :password, :password_confirmation).

By doing this, you prevent any mass assignment that could occur via your application’s forms—just because you don’t have a field for a given attribute doesn’t mean a hacker can’t add it to the request. This way you’re either forced you to manually set certain attribute values or, more usefully, provide a protected method to use when you want to set the value.

From a security perspective, using attr_accessible and attr_protected forces you to think about what should be editable and how to protect the ways in which your class’s attributes are set.

Use Non-database-backed Models

Although models in Rails are mostly based on ActiveRecord::Base or some other type of object mapper for a database, it’s important to remember that in MVC, the M isn’t restricted to database-backed models.

Using non-database-backed models can help to organize logic which might otherwise become muddy. For example, there are libraries that give you an ActiveRecord-like interface for contact form emails.

Using ActiveModel (available in Rails 3 and higher), it’s possible to take arbitrary objects that encapsulate a set of common behavior and use them as your models. Adding virtual models also makes it easier to adhere to RESTful controller design, as you can represent data other than database entries as resources. As a prime example, several popular authentication libraries in Rails now represent the user’s current authenticated session as a model, and I’ve personally implemented a password reset as a model.

When it comes time to interact with these models in your controller code, your code will be that much cleaner, as you can use the exact same approach as with database-backed models.

Virtual Attributes

If you find that you’re manipulating data before passing it to a model (for example, converting the type of an object), it’s likely time you started structuring your code to take advantage of virtual attributes.

Virtual attributes are a very simple idea—essentially, all you’re doing is defining your own getter and setter methods.

Let’s say you were using the following code to set a user’s name:

  1. @user = User.new(params[:user])
  2. @user.first_name, @user.last_name = params[:user][:full_name].split(“ ”, 2)

You could remove the second line, and instead add the following to your User model:

  1. def full_name=(value)
  2.   self.first_name, self.last_name = value.to_s.split(“ ”, 2)
  3. end

Whenever you set the full_name attribute, your model will now automatically set the first_name andlast_name attributes for you as well, even though full_name doesn’t exist in the database. Likewise, you’ll typically want to define a getter method, full_name, that returns "#{first_name} #{last_name}".

Using virtual attributes, you can use alternative representations of data in forms with relatively little effort. It’s also much simpler to test the logic in isolation, which is always a good thing.

Use Translations

As of Rails 2.2, the framework itself has shipped with strong support for internationalization (or i18n) out of the box. All you need to do is maintain a YAML file of translations, and use I18n.t / t in your code where there is data shown to the user. Essentially, the Rails i18n framework makes it easy to declare the map of an abstract context to a string.

From a developer’s perspective, using I18n is useful for more than just rolling your app out to more locales. When it comes time to rename something in your interface, having a single place to look for the string in question in order to replace it across the whole application is much quicker than scouring your code for every occurrence.

If you want to get started with Rails’ I18n framework, there is a very thorough guide made freely available on it by the community.

In Conclusion

There are literally hundreds of coding practices or techniques that can make your life as a Ruby on Rails developer easier, but I’ve tried to pick out ten that are broadly applicable to just about every project, and which are often ignored. Do you follow these practices already? Will you start? Do you have any others you’d add? Let me know in the comments.

Source: http://www.sitepoint.com/10-ruby-on-rails-best-practices/

 

Introducing Test-Driven Development with Rails 3

What We Need

For this to work, we’re going to have to implement three separate things:

  • A way to convert a given stored URL to a short code
  • A way to convert from a short code to a stored URL
  • A new, shorter route to fetch a URL from that.

Getting started, we’ll want to open up the existing test files. When we generated our URL model in the part one, Rails also generated a stubbed out test for us in test/unit/url_test.rb. Opening it up and taking a look, you should see something similar to:

1 require 'test_helper'
2 class UrlTest < ActiveSupport::TestCase
3   # Replace this with your real tests.
4   test "the truth" do
5     assert true
6   end
7 end

This is the general structure of a unit test in Rails 3 – the test method lets us declare a method (we also have setup and teardown to deal with maintaining a generalised environment for our tests) and we use asserts (e.g. the assert method call in the code above). Rails (and Test::Unit, the testing framework rails integrate) ship with several assertions out of the box that we can use – for a list, see the methods starting with assert_ at the rails api docs and this older cheatsheet for some of the standard test unit assertions.

Writing Tests

Next, we’ll add some test stubs—empty tests that we can fill out later. To do this, we need to work out exactly what we want to test in the most basic terms. Inside the URL test class, replace the existing test lines with the following:

1 test 'creating a url lets us fetch a short code'
2 test 'existing urls have short codes'
3 test 'converting a short code to an id'
4 test 'finding a url from a known short code'
5 test 'finding a url from a invalid short code raises an exception'

Next, from the command line, we can run these empty tests to verify they fail by running the following from our application directory:

1 rake test:units

Since we haven’t done anything other than write their names, we should get four failures.

Now, we’ll go through our tests 1 by and write them. To get started, fill them out one by one, replacing the test stub as you go:

01 test 'creating a url lets us fetch a short code' do
02   my_url = Url.create(:url => 'http://google.com/')
03   # The url should have a short code
04   assert_present my_url.short_code
05 end
06 test 'existing urls have short codes' do
07   my_url = Url.create(:url => 'http://google.com/')
08   # Force a fetch from the datbase
09   found_url = Url.find(my_url.id)
10   assert_present found_url.short_code
11   assert_equal my_url.short_code, found_url.short_code
12 end
13 test 'finding a url from a known short code' do
14   my_url = Url.create(:url => 'http://google.com/')
15   assert_equal my_url, Url.find_using_short_code!(my_url.short_code)
16 end
17 test 'finding a url from a invalid short code raises an exception' do
18   assert_raises ActiveRecord::RecordNotFound do
19     Url.find_using_short_code! 'non-existant-short-code'
20   end
21 end

In each of the tests, we test some facet of the expected model behaviour:

  • In our first test we check that once we create a URL, that it has a short code by calling the short_code method and invoking assert_present with its value.
  • In the second test, we create a URL, force-reload it from the database (to simulate fetching it at a later point in time) and then check that it also has a short code and more importantly that the found object has the same short code.
  • In the third test, we create a URL, and test that when we fetch it from the database (using our currently non-existent method find_using_short_code!) that it’ll return the same url.
  • In our last test, we check that when we give it an invalid short code, it raises an exception as expected.

Switching back to the command line and running our tests again using rake test:units, we should still see 4 failures. This is good—it means we have tests but haven’t actually implemented them yet.

Making Our Tests Pass

Now, we’re going to make our tests pass. In order to do this, we need to implement two methods. First, we the short_code instance method on the Url class and then find_using_short_code! class method.

In url.rb, we’ll add a method to generate a short code. For the moment, we’ll just use the base 36 value of id (e.g. 10 will be a):

1 class Url < ActiveRecord::Base
2   validates :url, :presence => true
3   def short_code
4     id.to_s 36
5   end
6 end

Re-running our tests, we’ll see 2 out of 4 of our tests now pass. Next, we’ll implement a method to find it from the id by doing the reverse conversion (taking a number from the base 36 value):

1 class Url < ActiveRecord::Base
2   validates :url, :presence => true
3   def short_code
4     id.to_s 36
5   end
6   def self.find_using_short_code!(short_code)
7     find short_code.to_i(36)
8   end
9 end

Running our tests one last time, we’ll see that they all now pass – we can now get and generate the short codes.

Source : http://rubysource.com/introducing-test-driven-development-with-rails-3/

Rhodes Application Generator

Rhodes utility is a generator which the user uses to create Rhodes applications, models, and tests (specs).

Generating an Application

You pass your application name to the rhodes app command as a parameter. The Rhodes utility will generate a default directory structure for your application, with default code for the generated files.

 

Usage: rhodes app name [options] [args]Generate a new rhodes application.Required:  name        - application nameargs (optional):  syncserver  - url to the source adapter (i.e. "" or "http://myacct.rhohub.com/apps/myapp/sources/")  zip_url     - optional url to zipfile download of bundle (this can be your RhoHub Bundle URL)options:    -p, --pretend                    Run, but do not make any changes.    -f, --force                      Overwrite files that already exist.    -s, --skip                       Skip files that already exist.    -d, --delete                     Delete files that have previously been generated with this generator.        --no-color                   Don't colorize the output    -h, --help                       Show this message        --debug                      Do not catch errors

 

For example, the following command generates an application named myspace.

 

$ rhodes app myspace

 

The generated application has the following directory structure and files.

 

myspace/    Rakefile    build.yml    rhoconfig.txt./app:    application.rb    index.bb.erb    index.erb    layout.erb    loading.html    loading.png./app/Settings:    controller.rb       home.bb.erb     home.erb        index.bb.erb        index.erb       login.bb.erb        login.erb       reset.bb.erb        reset.erb       wait.bb.erb wait.erb./app/helpers:    application_helper.rb    browser_helper.rb./icon:    <default application icons; modify these to have your own app icon>./public:./public/css:    <default set of css for different platforms>./public/images:    <default images used by js libraries>./public/jquery:    <jQuery js script with some rhomobile fixes>./public/jqmobile:    <jQuery Mobile js script with some rhomobile fixes>./public/js:    <default js libraries>

 

 

Adding a Model to Your Application

Once you have generated your application, you can add a model to it, and the model can have attributes. For example, if you have a store application, you can add a model named product, and attributes like brand, name, price, and quantity.

 

 

Usage: rhodes model [options] [args]Generate a new model for a rhodes application.args:  name        - model name  attributes  - list of one or more attributes (i.e. name,industry,progress), NO spaces between attributesoptions:    -p, --pretend                    Run, but do not make any changes.    -f, --force                      Overwrite files that already exist.    -s, --skip                       Skip files that already exist.    -d, --delete                     Delete files that have previously been generated with this generator.        --no-color                   Don't colorize the output    -h, --help                       Show this message        --debug                      Do not catch errors

 

For example, here is the command to generate a model named account, with the attributes name and industry.

 

$ cd myspace$ rhodes model account name,industry

 

 

This will generate the following files in the folder app/Account:

  • app/Account/index.erb – the template to display the list of objects
  • app/Account/edit.erb – the template to edit an object
  • app/Account/new.erb – the template to supply values to create a new object
  • app/Account/show.erb – the template to displays the selected object
  • app/Account/index.bb.erb – the template to display the list of objects on Blackberry
  • app/Account/edit.bb.erb – the template to edit an object on Blackberry
  • app/Account/new.bb.erb – the template to supply values to create a new object on Blackberry
  • app/Account/show.bb.erb – the template to displays the selected object on Blackberry
  • app/Account/account_controller.rb – contains the basic CRUD actions: index, new, create, edit, update and delete.
  • app/Account/account.rb – contains Account model definition

A placeholder for Account test specs will be generated in the app/test folder:

  • app/test/account_spec.rb – placeholder for Account test specs

Add test framework

To add a test framework to the application:

 

 

Usage: rhodes specAdd test framework to a rhodes application.

 

For example:

 

$ cd myspace$ rhodes spec

This will generate the following files in the app folder:

  • SpecRunner/controller.rb – contains index action, which start all tests
  • SpecRunner/index.erb – the template to display tests results
  • mspec.rb – contain all mspec required files
  • spec_runner.rb – contain spec framework initialization and generate list of spec files

If you are going to use mspec, then add mspec and fileutils extensions to your application’s build.yml file:

extensions: ["mspec", "fileutils"]

source : http://docs.rhomobile.com/rhodes/generator

 

 

Build Rhodes Application

This page describes how to build Rhodes Application on all of our supported platforms: iPhone, RIM Blackberry, Windows Mobile and Android.

All Platforms Prerequisites

Required Software

You should check to see that the required software in installed on your computer, such as Ruby and RubyGems. See the installation instructions.

Setting Up Rhodes Source Code

If you planning to modify or extend Rhodes, you will need the Rhodes source code. It is distributed under MIT license. You don’t need it if you are not planning to modify/extend Rhodes.

Rhodes source code is available on github.com. You will need Git to get it. If you used RhoStudio for Windows you probably already have Git installed on your system. Otherwise, load it fromhere.

To clone Rhodes to your local computer, execute git clone from the command line:

$ git clone git://github.com/rhomobile/rhodes.git
$ cd rhodes

Checkout the branch you are interested in (if not the master branch):

$ git checkout -f -b <branchname> --track origin/<branchname>

To keep your branch up to date, use the git pull command:

$ git pull

Add the bin folder of this clone to your path. On Linux/Mac it is typically done in the .profile file. On Windows, it is done using the Control Panel.

Configure your environment by running the rhodes-setup script. This will attempt to auto-detect installed SDKs. It will prompt you to verify the SDK paths or enter paths for SDKs that cannot be detected.

$ rhodes-setup

You don’t have to do it if you cloned sources, but if you want to build a Rhodes gem, do the following:

$ rake gem
$ gem install rhodes-[version].gem

Setting Up build.yml

By default application use latest Rhodes gem installed on computer.

If you wish to use special version of Rhodes or use Rhodes git sources :

sdk: /Library/Ruby/Gems/1.8/gems/rhodes-3.0.2

OR for Rhodes sources:

sdk: ~/Projects/rhodes

After installing new Rhodes gem(3.2.x over any version less then 3.2.x), you need also open a command line window, navigate to the directory of your Rhodes application, and run the following command:

$ migrate-rhodes-app

The migrate-rhodes-app will remove sdk line from your build.yml to use latest Rhodes gem, it also will upgrade application Rakefile.

Building a Rhodes Application for iPhone/iPad

iPhone/iPad versions of Rhodes apps must be built on Macintosh computers or on rhohub.com. The instructions below describe how to do this from either the Macintosh Xcode development environment or from the command line on your local Macintosh.

Prerequisites

To build for iPhone/iPad using you will need the following software installed:

 

Build a Rhodes Application with Xcode

If you wish to run your Rhodes application on an iOS device, you need to build and run it using an Xcode project.

Tell Rhodes to build from your Rhodes application.

$ rake switch_app

The switch_app command changes the rhobuild.yml in the Rhodes source code folder to point to your application, as in the following example for a Rhodes application named Store in the user’s home folder:

env: 
  app: /Users/NameOfUser/Store

Note that the switch_app command is only used when you run a Rhodes application within an IDE, such as Xcode: you run switch_app for each Rhodes application that you run in Xcode. The switch_app command does not affect Rhodes applications that you build and run on the command line.

Now run the following command to tell Rhodes to set up the Xcode environment for your Rhodes application:

$ rake build:iphone:setup_xcode_project

Then in the Rhodes source code folder (the path in your Rhodes application build.yml file), navigate to the /platform/iphone folder and open rrhorunner.xcodeproj. This will open your Rhodes application in Xcode.

In the Xcode Scheme menu, select the proper scheme before you build and run your project. Click on the Scheme menu.

xcode scheme

Select the Scheme for your project under rrhorunner. You can select to run in the simulator.

xcode scheme simulator

Now you can build and run in Xcode to run your project in the iOS simulator.

If you are an Apple developer, you can run your Rhodes application on your iOS device. In Xcode, select your rhorunner target, click on the Build Settings tab, and see that your code signing information that you installed as an Apple developer is set up and selected.

xcode build settings

Plug in your iOS device. In Xcode, under Scheme, select iOS device under rhorunner. Then build and run.

xcode scheme device

For more information on running on your iOS device from Xcode, go to the Apple developer site, go to the iOS Developer Library, and search on “managing devices”, or “run applications on a device,” or similar.

You can edit your Rhodes code for your Rhodes application in a text editor, save your changes, do a Clean in Xcode so that your changes will register in Xcode, and then rebuild and run your project from Xcode.

The resulting application package (*.app) is located in your Rhodes source code folder under /platform/iphone/build/, in a folder named like [Debug/Release]–[iphoneos/iphonesimulator]/rhorunner.app.

Building and Releasing on App Store

Once you have the application building with Xcode as described above, it is treated as any other iPhone application when it comes to signing and distributing to the app store.

Restoring rrhorunner.xcodeproj

To restore the Xcode rrhorunner.xcodeproj to its original state:

$ rake build:iphone:restore_xcode_project

Building iPhone Application from the Command Line

Unlike building the application from the Xcode GUI, when you build the application from the command line, use the rake command from the directory of the application that you had just generated with rhogen.

From the command line, navigate to the folder for your Rhodes application.

To run your Rhodes application in the iPhone simulator, run this rake command:

$ rake run:iphone

Building the Application for the iOS Device

After you have modified and debugged your Rhodes application, you can prepare your application to install to your iOS device.

Modifying the build.yml

First, in your application’s build.yml file, change sdk to iphoneos instead of iphonesimulator, configuration to Release instead of Debug, and add information such as codesignidentity.

iphone:
    sdk: iphoneos4.3
    configuration: Release
    codesignidentity: "iPhone Developer"
    entitlements: ""

build.yml settings

The default build.yml settings generated for iphone are:

name: myapp
version: 1.0
iphone: 
  provisionprofile: 
  sdk: iphonesimulator3.0
  entitlements: 
  codesignidentity: 
  configuration: Debug
  emulator: 3.0
  emulatortarget: iphone
  BundleIdentifier: com.yourcompany.yourapp
  BundleURLScheme: yourapp
  • name: name of your application. Will show on screen (iPhone application bundle display name)
  • version: version of your application. iPhone application bundle version
  • provisionprofile: The UUID of your provisioning profile to use when signing.
  • sdk: The version of sdk used to build. Typically iphonesimulatorX.X or iphoneosX.X
  • entitlements: propertylist file for entitlements for your build. Typically is Entitlements.plist
  • codesignidentity: The name of the code signing identity to use when signing for device.
  • configuration: Debug/Release/Distribution
  • emulator: version of emulator for run application
  • emulatortarget: device family for simulator (iphone/ipad)
  • BundleIdentifier: bundle identifier – used in provisioning profile
  • BundleURLScheme: bundle URL scheme of your app (used for opening your application from another application by using custom URL scheme)

**

  BundleIdentifier and BundleURLScheme can contain only next symbols : “a”–“z”, “A”–“Z”, “0”–“9”, “–”, “.” !

 

Here is an example of the iPhone settings in build.yml for a finished application:

name: JS App
version: 1.0
iphone: 
  provisionprofile: E5931D39-CA68-48E4-A3AF-BB538E1C8CE6 
  sdk: iphoneos4.2
  codesignidentity: "iPhone Developer: John Smith (MF99RW67WY)"
  entitlements: ""
  configuration: Release
  emulator: 4.2
  emulatortarget: ipad
  BundleIdentifier: com.johnsmithcompany.jsapp
  BundleURLScheme: jsapp

Creating Your Application Package

Now you can create your .app file with this rake command:

$ rake device:iphone:production

The package named your application name.app will be placed to <your application folder>/bin/target/iOS/[sdkname]/[configuration]/[your application name].app if you are using Rhodes from 2.2.4 version.

Result package named rhorunner.app will be placed to <sdk directory>/platform/iphone/build/[Debug/Release/Distribution]-[iphoneos/iphonesimulator]/rhorunner.app if you are using Rhodes before 2.2.4 version.

Installing Your Application Package to Your iOS Device

Use iTunes for installing your application package (your_application_name.app) to the iOS device:

  • Open iTunes.
  • Under Library, select Apps.
  • Drag and drop your application package into the Apps screen.
  • Connect your device to iTunes.
  • Under Library, select your device.
  • Select the Apps tab in your iTunes device screen.
  • In the Sync Apps list, check your application.
  • Perform a sync. Your application is installed to your device.

 

Build for Android

Prerequisites

  • OS compatible with Android SDK
  • Follow All Platforms Prerequisites
  • Download the Android SDK Starter Package
    • Run <sdk>/tools/android on OSX/Linux or <sdk>/SDK Setup.exe on Windows
    • Go to Settings > check Force https://... sources to be fetched using http:// and press Save & Apply.
    • Go to Available > Expand https://dl-ssl.google.com
    • Download the latest SDK version, latest platform (SDK Platform 2.2, for example) and latest “Google APIs” available.
  • Set the environment variables ANDROID_HOME to where you installed the SDK, and add<sdk path>/tools to PATH
  • Download and install the Android NDK
  • Run rhodes-setup and tell Rhodes where you installed the Android SDK and NDK

In case if you are planning to work with native geo mapping (MapView interface), two things should be done:

  • Android Maps API key should be retrieved from Google. Follow these instructions to get it. When key received, put it in your application’s build.yml or share it across all your applications by adding it to rhobuild.yml. Note that the apikey value must match a certificate used to sign an application (the key is different for debug and production signed build and debug key cannot be shared between different build computers).

    android:

    apikey: "GOOGLE-API-KEY-FOR-ANDROID"
  • Enable ‘mapping’ in your application’s build.yml (or in <rhodes-root>/rhobuild.yml):

    android:

    mapping: yes

If you are using Eclipse (Optional) please follow these instructions on how to increase Java memory space to use Android.

Please check your applications and change how you include css files into html pages.

For example, you will need to replace

<style type="text/css" media="screen">
    @import "/public/js/iui/iui.css"; @import "/public/css/rho.css";
</style>

with

<link rel="stylesheet" href="public/js/iui/iui.css" type="text/css">
<link rel="stylesheet" href="public/css/rho.css" type="text/css">

Otherwise your css files will not be loaded in Android 1.5 (and higher)

Device capabilities settings in build.yml

Attention ! On Android you should specify list of device capabilities need for you application. By default there are not any capabilities enabled ! This is important because all defined capability produce special lines in AndroidManifest.xml specific to Android platfrom. Without enabled permission application can not access to device functions. List of capabilities related to changes in AndroidManifest – add or remove this items in “capabilities” section in your build.yml:

audio
camera
gps
network_state
phone
pim
record_audio
vibrate
bluetooth
calendar
sdcard
push

Set up minimal Andoid SDK API level

The minimal API level supported by Rhodes is 4 (Android 1.6) It is possible to set greated minimal API level with build.yml. This will restrict installing an application on any Android OS prior to 3.0:

android:

minSDK: 11

Building app and running it in emulator from the command line

 

make sure that your PATH has the path to java bin.

 

From the command line, in your rhodes application directory, run:

$ rake run:android

It will create (if needed) new virtual sdcard for emulator, then check if emulator is already running (and start if not) and upload application there. You can specify version of emulator you are want to run in your application’s build.yml:

android:
  version: 2.1

You can also specify emulator AVD name (see ‘Android SDK and AVD Manager’).

android:
  emulator: myDeviceEmulator20

Disable Android title in application :

android:
  android_title: 0

Setup fixed screen orientation for application (writed to Manifest, possible values: “portrait”, “landscape”) :

android:
  orientation: portrait

If the rake command gets stuck you can kill the command window, open another window, run:

$ adb start-server
$ rake run:android

 

If you didn’t run your Android simulator yet or don’t have AVD configuration set, you will be asked a few questions about emulator configuration. You should answer “yes” for most questions or use default answers. As a result new AVD configuration will be created.

 

To uninstall application from emulator, run:

$ rake uninstall:android

Building app and running it on the device from the command line

If you have an Android device, you can develop and debug your Android applications just as usual. Launching your apps on a device works just the same as on the emulator, but there are a few things to do before you can start. Please check corresponding Android documentation.

You can verify that your device is connected by executing:

$ adb devices

If connected, you’ll see the device name listed.

If your machine doesn’t “see” the device as connected, try killing the adb process first:

$ adb kill-server
$ adb install <filename>.apk

After you have your device connected, in your rhodes application directory, run:

$ rake run:android:device

This will build your application and sign it with auto-generated self-signed certificate

To uninstall from the device, run:

$ rake uninstall:android:device

If you want to build production version, edit your application’s build.yml as below:

android:
  production:
    certificate: path/to/your/developer/certificate
    password: "password-of-the-certificate"
    alias: "keystore.alias"

This will use specified certificate to sign application. If certificate is not found, it will be auto-generated. In this case you’ll be prompted with several questions like your name, organization etc. The path to certificate may be absolute or relative to your app directory. If you don’t want to use auto-generated certificate, refer to the these instructions on how to create it manually.

After that run:

$ rake device:android:production

Signed APK will be located in <rhodes-app-dir>/bin/target. To install application on the device run:

$ adb -d install -r <rhodes-app-dir>/bin/target/<app-name>_signed.apk

Building app in Eclipse

Please note: It is only Google API target (with Google mapping API) supported for Eclipse

Create a new workspace in the following directory: <Rhodes>/platform/android

Go to the Window > Preferences

Click on Android node in the tree and specify file path to the installed Android SDK (For example:E:\android\android-sdk-windows)

Import all projects from the following directory: <Rhodes>/platform/android

If you have set the option to build sources automatically all stuff will be compiled just after the import.

Select Properties from the Rhodes project context menu and select one of latest Google API target for Android.

Check bin directory. You should see Rhodes.apk file created. It will be signed with debug key provided with SDK.

Now you are ready to install your application on device and/or emulator.

In case of troubles in Eclipse while setting up the Android SDK and target try “Rhodes project context menu” > “Android Tools” > “Fix Project Properties”.

It is possible your application has stopped unexpectedly just after the first build. In this case try to copy autogenerated java source files from the application folder /bin/tmp to the Rhodes project.

Getting application log from device or emulator

To get application log from device or emulator, from your application folder or from root of rhodes source tree (place where rhobuild.yml is located), issue command:

$ rake device:android:getlog

Or

$ rake emulator:android:getlog

Application log will be pulled from device/emulator and stored in your application directory with name RhoLog.txt.

To see all emulator messages run ‘adb logcat’ and start application on emulator

To see all device messages run ‘adb -d logcat’ and start application on device

Build for BlackBerry

Blackberry SDK for Mac doesn’t come with simulators so far. So for now we would assume you are using Windows to develop for BB.

Prerequisites

  • Follow All Platforms Prerequisites
  • Load and install Blackberry JDE version 4.6.0 or higher(5.0 or higher recommended for simulator usage) from here
  • Run ‘rhodes-setup’ to specify Blackberry JDE paths or edit /rhobuild.yml manually:

    env: 
        paths: 
          5.0: 
            jde: <jde_5.0>/components
            sim: 9550
            mds: <jde_5.0>/components/MDS
  • Read about Blackberry Browser limitations of CSS, HTML and JavaScript. Get relevant documentation from here.

Build application using rhodes gem

Before you build edit build.yml from the application directory. Set the bbver to the target BB OS that you are building for. For example:

bbver: 5.0

To build and run using Blackberry simulator 5.0 and higher

Starting from Blackberry JDE 5.0, simulator supports loading application cod-files to simulator without restart. This feature greatly improve Blackberry development perfomance. There are 2 possible scenarios available:

  • Load application cod-file manually using Simulator menu: ‘File\Load Blackberry application or theme…’:

    $ rake run:bb:startsim
      $ rake package:bb:production_sim

    In simulator window open menu: ‘File\Load Blackberry application or theme…’ and choose app cod-file:‘/bin/target//<app_name.cod>’

    After application modification:

    $ rake package:bb:production_sim

    And reload application cod-file in simulator using menu.

  • Use rake commands to reload app on simulator.

    $ rake run:bbapp
    Start application on simulator and DO NOT close application in simulator. After application modification:
    $ rake run:bbapp
    In case of simulator errors:
    • Try load application cod-file manually.
    • Try to uninstall application: select application icon on simulator and press Menu\Delete
    • Close simulator and run clean.bat in simulator folder

To build and run using Blackberry simulator

Run in application root directory:

$ rake run:bb

Launch application from the simulator’s Downloads menu item for 4.6 or from Main menu screen on 4.3 and below. Do not close Simulator manually after you have done testing. Script will restart simulator for you.

Modify your application and run run rake script again:

$ rake run:bb

To see application log change log settings in rhoconfig.txt. Run your application and see log file at <simulator folder>\sdcard\rho\<app_name>\RhoLog.txt

To switch log on while running your application select menu\log\options form the application menu and set log level to Info and Message classes to APP or to *.

To clean all data (database and log) go to ‘\sdcard` and remove rho folder. If you use Persistent Storage mode – remove app or run clean.bat in the simulator folder.

Some known issues while building for BB simulator

Run rake config:checkbb and see are any problems reported

Run rake scripts from windows console. Do not use bash or similar tools.

When emulator starts, open Blackberry Internet Browser and browse for some web site. If you are unable to browse:

  • check that MDS is running – it should be console window started with emulator.
  • open manage connection (blackberry menu button)\check Mobile Network

Check your JAVA_HOME environment variable: it should NOT contain ‘bin’ at the end.

Do not use ‘localhost’ or ‘127.0.0.0’ for sync server address if you host sync server on your machine. Use local computer name instead.

To build application for the device

You have to sign application before loading it to device. Go here to get Code Signing Keys.

Once you have Code Signing Keys files (sigtool.csk and sigtool.db) you should put them in the ‘bin’ folder of your Blackberry jdk and sign your application.

If your target device is Blackberry JDK 4.3 and later, you can provide password in the rhobuild.yml file (located in the Rhodes SDK folder) in the ‘build’ section:

build:
  bbsignpwd: <password>

Run:

$ rake device:bb:production

Built application will be available at <application_directory>/bin/target. For example, if you rake:bb:production, the files will be in a directory named for the SDK version, like /bin/target/4.6/ota-web. You should see many .cod files and a single .jad file.

You may deploy it to the device now. To do that upload .jad and all .cod files to a web server, then open the .jad file from the browser on your blackberry device. You may use rhohub.com Gallery feature to host your builds as well.

Some known issues while building for BB device

After you get your CSI-file from Blackberry, you have to register them. If after dbl-click you will see message “Already registered” see instructions here: Incorrect password error when attempting to register signature keys

After press Yes in dialog ‘Would you like to create a new key pair file’ – nothing appear. No dialogs, no error messages, just nothing then this is a problem with Java SDK and Blackberry SDK versions. See more information here:

If you still have a problems then manually register CSI files

Signature files can be only registered once per computer. If you register them for example in 4.6 Blackberry SDK , you can copy sigtool.csk and sigtool.db to bin directory of any other BB SDK

There is a problem with network on BlackBerry simulators under Windows 7. It causes syncing failure. There are two workarounds for this issue. One is to use MDS for network connection in simulator (build script does this automatically). The second workaround is to emulate WiFi connection in the simulator.

Application log on the device

The log is written to the file ‘rholog.txt’:

  • If your device has SD card log will place to <Media Card>\Rho\<app name> folder.
  • If your device doesn’t have SD card log will place to <Device Memory>\home\user\rho\<app name>.

To see or copy log file to your computer:

  • Add menu item Log to your application menu
  • Call RhoConf.show_log or RhoConf.send_log somewhere in your app (for example on the settings page)
  • Open Media application on the Phone, select Menu\explore. You can view log file or send it via bluetooth
  • If you have SD card: Phone options\memory\Mass storage support – ON, save. Then connect device to the computer via cable and you will see USB disk drive in computer explorer. Copy rholog.txt to computer.

 

Do not forget to turn ‘Mass Storage support’ OFF, otherwise Rhodes wouldn’t be able write to the files!

 

Connectivity on the device

If your phone has Wifi connectivity Rhodes will use it without any additional efforts. In case of GPRS, you should :

  • Setup mobile network: Phone Options\Mobile Network\Data Services ON, Connection preferences: Should be not WiFi-Only.
  • Setup APN address: Phone Options\Advanced settings\TCP/IP/APN settings enabled. APN should address specific for your provider (wap.cingular for example).

Event log from device

Read Blackberry article on how to enable, access, and extract the event logs on a BlackBerry smartphone.

Now you should be able to extract a full copy of BlackBerry smartphone event logs to a text file using loader.exe on a computer.

Connect the BlackBerry smartphone to the computer using a USB cable.

Open the command prompt and type:

$ cd c:\Program Files\Common Files\Research In Motion\AppLoader

On a 64-bit system, type:

$ cd c:\Program Files (x86)\Common Files\Research In Motion\AppLoader

Type:

$ Loader.exe /eventlog c:\log.txt

The log.txt file is the extracted log and should appear on the C:\ drive.

 

To obtain the Loader.exe tool, install BlackBerry® Desktop Manager 4.7 or later, or visithttp://na.blackberry.com/eng/update/ to check for updates for the BlackBerry smartphone that will install the necessary components to your computer.
On some Windows Vista™ and Windows® 7 computers, even though c:\ was specified, the Java Event logs might be saved to the following location: c:\Users\<username>\AppData\Local\VirtualStore\Program Files\Research In Motion\BlackBerry\Apploader

 

Build rhodes from the source code using Eclipse

  • You should have Blackberry Eclipse IDE installed.
  • Please make sure that there are no .metadata folder in rhodes\platform\bb folder.
  • Go to <rhodescheckout> and run:

    $ rake build:bb:devrhobundle
  • Run eclipse and choose rhodes\platform\bb as a workspace directory. Do not create workspace!

  • Open menu Window\Preferences
    • Blackberry java plug-in\Warnings – check all 3 chekboxes to suppress all warnings
    • Java\Compiler – set Compiler compliance level to 1.4
  • Go to File\Import… menu. Select General\Existing projects into Workspaceworkspace node. Press Next.
    • Browse for <rhodes>\platform\bb\RubyVM. Press Finish. The project will be automatically build.
    • Browse for <rhodes>\platform\bb\Hsqldb. Press Finish. The project will be automatically build.
    • Browse for <rhodes>\platform\bb\Rhodes. Press Finish. The project will be automatically build.
  • Go to Run\Debug Configurations – double click on Blackberry simulator
    • select all projects in Projects tab
    • got to Simulator tab, select Memory, check Use PC file system for SDCard files, addRho to PC file system for SDCard files edit box
    • Press Debug

Congratulations! It is all done.

Known issues with Eclipse build

Sometime BB Eclipse project is checked in in a wrong state and wouldn’t build correctly after loading:

  • You need to make sure every sub-project is activated for BlackBerry: right-click on the sub-project and select Activate for BlackBerry menu item.
  • Check and set project dependencies correctly: select Project/Properties... menu and navigate to BlackBerry Project Dependencies…. Set following dependencies:
    • PersLite doesn’t have any dependencies
    • PersImplJSR75 depends on PersLite
    • RhoBundle depends on RubyVM
    • RubyVM doesn’t have any dependencies
    • rhodes depends on PersLite, PersImplJSR75, RhoBundle, RubyVM

Rebuilding After Code Changes

Go to <rhodescheckout> and run:

$ rake build:bb:rhobundle

It should re-create rhodes\platform\bb\RhoBundle\RhoBundle.jar

Right click on RhoBundle project in Eclipse and select Refresh. It should rebuild rhodes and RhoBundle. You can see messages in Builder Console. OR Just Clean all projects.

Eclipse simulator debug instructions

Open Debug\Open debug dialog... from toolbar (small bug icons). Dbl-click on Blackberry simulator node.

Go to Simulator page and choose Profile other than Default. Check ‘Launch Mobile Data System Connection service with simulator’ checkbox.

 

you may have to install MDS on your computer if it is not installed.

 

Press Debug button. Simulator starts. Eclipse may ask you about missing debug files, press ‘Don’t ask me again button’.

You can also clean emulator and start emulator again:

$ run <JDE_HOME>\simulator\clean.bat

Press Menu button on emulator. Go to Downloads, run Rhodes

Build for Symbian

Note that Symbian versions of your Rhodes app must be built in a Windows environment.

Prerequisites

If you want to build for Symbian device you have to install QT and QT Mobility for Symbian on your device. You can find installation files in QT SDK folder like below:

For Symbian 9.4

    QT - C:/QtSDK/Symbian/sis/Symbian1/Qt/4.7.3/qt.sis
    (install it only on disc C:, before install pls close all opened applications)

    QT WebKit - C:/QtSDK/Symbian/sis/Symbian1/Qt/4.7.3/qtwebkit.sis
    QT Mobility - C:/QtSDK/Symbian/sis/Symbian1/QtMobility/1.1.3/qtmobility.sis

    For Symbian 9.5

    QT - C:/QtSDK/Symbian/sis/Symbian3/Qt/4.7.3/qt.sis
    (install it only on disc C:, before install pls close all opened applications)

    QT WebKit - C:/QtSDK/Symbian/sis/Symbian3/Qt/4.7.3/qtwebkit.sis
    QT Mobility - C:/QtSDK/Symbian/sis/Symbian3/QtMobility/1.1.3/qtmobility.sis

Then open file – C:/QtSDK/Symbian/SDKs/Symbian1Qt473/epoc32/include/cntdb.h and replace below two strings:

CContactConverter& CContactDatabase::ConverterL(const TUid& aFormat);
CContactConverter& CContactDatabase::ConverterL(const TUid& aFormat, const TInt64 aContactFieldFilter, MConverterCallBack* aCallback, const TVCardVersion aVersion,const TBool aExportTel);

with these strings:

CContactConverter& ConverterL(const TUid& aFormat);
CContactConverter& ConverterL(const TUid& aFormat, const TInt64 aContactFieldFilter, MConverterCallBack* aCallback, const TVCardVersion aVersion,const TBool aExportTel);

 

You have to install Rhodes on the same local disk with QtSDK!

 

Build application from the command line

Add pathes to Qt SDK and MS Visual Studio 2005 to rhobuild.yml in the Rhodes folder:

env:
      paths:
        qtsymbian-sdk: C:/QtSDK
        msvs2005: C:/Program Files/Microsoft Visual Studio 8

To build and run application on emulator(Visual Studio 2005 only) :

$ rake run:symbian

To build application sis-file for the device:

$ rake device:symbian:production

 

This command creates two sis-files: signed for testing and unsigned for production signing. See /bin/target/sym folder for sis-files.

 

To clean all binaries run:

$ rake clean:symbian

 

If the clean rake task doesn't respond long time while it is being executed then stop it and delete folder like this: C:/QtSDK/Symbian/SDKs/Symbian1Qt473/epoc32/BUILD/.../rhodes
If You want to use your own UID for application you can redefine it in build.yml. You can find information about UID here - http://www.developer.nokia.com/Community/Wiki/UID_Q&As_(Symbian_Signed)

 

Build for Windows Mobile

Note that Windows Mobile versions of your Rhodes app must be built in a Windows environment.

Prerequisites

  • Follow All Platforms Prerequisites
  • .NET Compact Framework
  • Windows Mobile 6 Professional SDK(s)
  • Microsoft Active Sync 4.5 for Windows XP; Windows Mobile Device Center for Windows Vista or higher
  • Microsoft Device Emulator 3.0 for Windows Vista or higher
  • Visual Studio 2005 Service Pack 1 installed or Visual Studio 2008.
  • 7-zip

 

It is a good idea to install Windows Mobile 6 Professional last, since it needs to be installed after Visual Studio, and since the Windows Mobile 6 Professional install process will tell you if you forgot to install any of the other prerequisites.

 

Allow DMA Connections

On Windows XP, open ActiveSync main window and open the File menu; on Windows Vista and above, open Windows Mobile Device Center and click Mobile Device Settings.

Select Connection Settings, then select the checkbox “Allow connections to one of the following.”

Select “DMA” from the list box. DMA Connection is required to work with the Windows Mobile emulator.

Add Paths

Add path to vcbuild.exe and CabWiz.exe to rhobuild.yml in the Rhodes folder (example location:C:/InstantRhodes/ruby/lib/ruby/gems/1.8/gems/rhodes-3.0.2).

env:
  paths:
    vcbuild: `C:/Program Files/Microsoft Visual Studio 8/VC/vcpackages/vcbuild.exe`
    cabwiz: `C:/Program Files/Windows Mobile 6 SDK/Tools/CabWiz`

On 64-bit installations:

env:
  paths:
    vcbuild: `C:/Program Files (x86)/Microsoft Visual Studio 8/VC/vcpackages/vcbuild.exe`
    cabwiz: `C:/Program Files (x86)/Windows Mobile 6 SDK/Tools/CabWiz`

Build and Run application on device or emulator (Visual Studio 2008 only):

To build cab-file, install it, and run application on emulator, run:

$ rake run:wm:cab

Before you install the application on your Windows Mobile device, first connect your device via USB cable. Then check that your device is connected with ActiveSync on Windows XP or with Windows Mobile Device Center on Windows Vista or above.

To build cab-file, install it, and run application on device, run:

$ rake run:wm:device:cab

After the build process completes, the device will ask you to install the app. Disconnect the USB cable from the device before you install.

Build application cab-file for the device

$ rake device:wm:production

If you want the application to be signed automatically during the build process, please add the ‘wmsign’ key with full path to your code signing certificate to the ‘build’ section of rhobuild.yml file:

wmsign: <disk:/path/MySign.pfx>

You can find more information about Windows Mobile code signing at:http://msdn.microsoft.com/en-us/windowsmobile/dd569132.aspx

Deploy application on device

First, connect your device to your computer. You can use USB-cable, bluetooth or any other method. To use computer internet, start ActiveSync or Windows Mobile Device Center.

You can use rake tasks to deploy the application. See the previous section, ‘Build application from the command line.’ The device should be connected via USB-cable.

Manually copy the .cab file to the device. For example, you can use the device File Explorer to display the .cab file that is on the computer. Click on that .cab file and the installation process will be started; after it is finished, you should see the app icon on your device in Programs.

Build from IDE

Checkout the rhodes source code from github (you have this source code already if you installed Instant Rhodes).

Open <source-code-root>\platform\wm\rhodes.sln in Visual Studio (example location for :C:/InstantRhodes/ruby/lib/ruby/gems/1.8/gems/rhodes-3.0.2).

In Visual Studio, select Windows Mobile 6 Professional and build Release configuration.

Edit the file rhobuild.yml in the Rhodes folder:

  • Check that the path to Cabwiz is defined, for example, C:/Program Files/Windows Mobile 6 SDK/Tools/CabWiz.
  • Define the path to your application folder.

Run

$ rake build:wm:devrhobundle

Make sure you cradle your emulator (menu Tools/Device Emulator Manager/Select Running Emulator/Actions/Cradle)

Copy rhodes.exe and rhobundle (located at <source-code-root>\platform\wm\bin\Win32\rhodes\Debug\rho) created at the previous step to the device: My Computer\Mobile Device and folder in Program Files on that device (for example,\Program Files\rhodes). You can first delete the contents of \Program Files\rhodes\rhofolder on your device if you want to ensure there are no old files left over.

If you changed your application, then recompile your application code by running the following command again, and copying rhobundle and rhodes.exe again:

$ rake build:wm:devrhobundle

If you changed your application and built it using rake tasks, then to compile your application:

$ rake device:wm

Copy <your_app_directory>\bin\target\rhodes.cab content to \My Documents\ on your device or the emulator, execute that .cab to install the app, and then run the installed app to see the changes.

Logging

To read the log file from the emulator or your device:

  • Connect to the device or emulator using ActiveSync or Windows Mobile Device Center.
  • Press explore on ActiveSync window, File Management on Windows Mobile Device Center.
  • Navigate to My Device\Program Files\<your_app_name>\rho\rholog.txt

Build for Windows

Prerequisites

  • Follow All Platforms Prerequisites
  • Visual Studio 2005 Service Pack 1 installed, Visual Studio 2008 or Visual Studio 2010 (Express editions are also supported)
  • WTL : http://wtl.sourceforge.net/ :
    • unzip to folder: \VC\WTL
    • open in Visual studio menu Tools\Options\Projects and solutions\VC++ directories. Select platform – Win32; Show directories for – Include files; Add – $(VCInstallDir)wtl\include

Build application from the command line

Make sure that path to vcbuild.exe (something like C:\Program Files\Microsoft Visual Studio 8\VC\vcpackages) is in your PATH env variable. The list of paths which should be in PATH env variable:

C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;C:\Program Files\Microsoft Visual Studio 8\VC\BIN;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin

If you use Visual Studio 2010 : add path to msbuild to rhobuild.yml in rhodes folder:

env:
  paths:
    vcbuild: msbuild

To build and run emulator run:

$rake  run:win32

To clean all binaries run:

$rake clean:win32

Logging

Rholog.txt is placed in <rhodes folder>\platform\wm\bin\win32\rhodes\Debug\rho

Build for Windows Phone 7

Prerequisites

Application changes

  • Add to application build.yml productid GUID. For example:

    wp:
        productid: 632621d0-5ecb-012e-2c97-482a1411c191

 

When you use rhodes command to generate application, productid is generated automatically

 

  • Windows Phone 7 does not support POST method in HTML forms. So you have to change all form method to GET or use javascript to do it:

    Copy file:

    <rhodes>\res\generators\templates\application\public\js\wp7.js
    
      to your application public/js folder

    Modify layout.erb:

    <%if System::get_property('platform') == 'WP7' %>
          <script src="/public/js/wp7.js" type="text/javascript"></script> 
      <% end %>
    
      <% if System::get_property('platform') == 'WP7' %>
          <body onload="wp7_change_forms_action_to_get()">
      <% else %>
          <body>
      <% end %>
          <%%= @content %>
      </body>

    This script just replace FORM action to GET:

    function wp7_change_forms_action_to_get() {
          for(i=0;i<document.forms.length; i++)
          {
              document.forms[i].method = "GET";
          }
      }

You can use Rhodes Application Generator to see application code with all this changes

 

in form action when using url_for specify :action => :create to call create controller method

 

Build and run using Rhodes gem

  • Install Rhodes gem

  • Run application simulator:

    $rake run:wp
  • Run application device:

    $rake run:wp:device
  • See log in application folder : rholog.txt

 

When running on device you may need to disconnect USB cable from device to see log

 

  • After Application code modifications, run rake commands. DO NOT close simulator!

Build from sources

  • Checkout rhodes source code from github
  • Get IronRuby master branch to parent folder of rhodes:

    $ git clone https://github.com/IronLanguages/main.git

    rename IronLanguages folder to IronRuby

  • Build IronRuby(Once)

    rake build:wp:ironruby

Build from IDE

IronRuby

  • Copy folder rhodes\platform\wp7\IronRuby\Languages to IronRuby
  • Open IronRuby\Solutions\Ruby.sln in VS 2010 or VS Express 2010 for C#.
  • Select ‘Silverlight3Debug|Any CPU’ or ‘Silverlight3Release|Any CPU’ in solution configuration and build solution

Rhodes

  • Open rhodes\platform\wp7\rhodes.sln in VS 2010 or VS Express 2010 for Windows Phone.
  • Select Debug or Release configuration, Windows Phone 7 Emulator target and build solution.
  • Run emulator by pressing Start Debugging or Start Without Debugging
  • After Application code modifications , build Rhodes solution and Start Debugging. DO NOT close emulator!
  • See log in VS output console (Debug mode only)

How to set application name and icon

Application Name

In the build.yml in your application folder there is an entry “name”. This is the display name that the user will see on the device. Example:

name: My Own App

Application Icon

Place your image to use as an icon in a folder called icon in your application. If you created an app called testapp then the folder would be testapp/icon. The icon should be namedicon.png and icon.ico for Windows Mobile. Starting from iOS 4.0, Apple require three icons for application: 57x57, 72x72 and 114x114 pixels. Prepare such files, name them as icon57.png,icon72.png and icon114.png and place into icon folder

testapp/
    build.yml
    Rakefile
    rhoconfig.txt
    app/
    public/
    icon/
        icon.png
        icon.ico

iPhone using xCode

  • Target->info->General->Name
  • Target->info->Build->Product Name (for all configurations)
  • rhodes\platform\iphone\icon.png, icon57.png, icon72.png, icon114.png – change to your icons
  • check rhodes\platform\iphone\Info.plist it should contain BundleName=${PRODUCT_NAME}

Windows Mobile

Windows Mobile Shell program caches program icons. This cache is cleared only when device or simulator is restarted. So if you change icon of application, you have to restart device/simulator(uninstall/install is not enough).

Symbian

You can change icon for your Symbian application replacing icon.svg which is in your application icon folder with a new one.

 

 

source : http://docs.rhomobile.com/rhodes/build

 

Set Up An Ubuntu Local Development Machine For Ruby On Rails

Ruby On Rails? Ubuntu?

What are Ruby on Rails and Ubuntu? In short, Ruby on Rails is a Web development framework that lets you create Web applications using the Ruby programming language. As the official website states, “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.”

Ubuntu, meanwhile, is a “Debian-derived Linux distribution that focuses on usability.” It has been the most popular Linux distribution for the last couple of years. And even better, both Ruby on Rails and Ubuntu are open source and, therefore, completely free to use.

The Ubuntu Logo

A Quick Overview

In this tutorial, we’ll install Ruby and RubyGems using the Ruby Version Manager (RVM) script. And we’ll install Rails and Capistrano in turn using RubyGems. The machine will also feature version control, provided by Git and a PostgreSQL database. A fresh installation of Ubuntu and a working Internet connection are assumed, but these steps should work on most (Debian- and Ubuntu-based) Linux distributions.

At the time of writing, the latest versions are Ubuntu 10.10, Ruby 1.9.2 and Rails 3.0.7. This tutorial was also tested on Ubuntu 10.04 and the upcoming Ubuntu 11.04 release.

During this tutorial, we will make extensive use of the Linux command line. Therefore, I have added a small glossary at the end of this article describing the relevant Linux commands.

Getting Up To Date

First, let’s get up to date. Log into your machine as a user with administrative (or sudo) rights, and open a terminal window. The commands rendered below need to be entered in this terminal window. The dollar sign ($) is your command prompt, and the rest is as simple as typing the command and hitting “Enter.”

The first three commands will then update the package lists, upgrade currently installed packages, and install new packages and delete obsolete packages. This will give you a machine that is fully up to date. The final command will reboot the machine, which is good practice after updating a large number of packages.

1 $ sudo apt-get update
2 $ sudo apt-get upgrade
3 $ sudo apt-get dist-upgrade
4 $ sudo reboot

Prepare Your Machine For RVM

After the machine has rebooted, log back in and open a terminal window. The RVM script needs some packages in order to be installed, namely Curl and Git. Curl is a tool to transfer data using a range of protocols (such as HTTP and FTP). And “Gitis a free and open-source distributed version control system, designed to handle everything from small to very large projects with speed and efficiency.” Git is the choice for version control among most Ruby on Rails developers.

1 $ sudo apt-get install curl
2 $ sudo apt-get install git-core

The Git Logo

Configure Git

Git will be used by the RVM script, and we’ll be using it in part 2 of this tutorial. So, after installing the packages, let’s take a little time to configure it. Configuring Git is easy: just provide a user name and email address.

1 $ git config --global user.name "Your Name"
2 $ git config --global user.email your-email@address.com

For example:

1 $ git config --global user.name "John Doe"
2 $ git config --global user.email johndoe@mail.com

Install RVM

Now we can install RVM. RVM stands for Ruby version manager and “is a command-line tool that allows you to easily install, manage and work with multiple Ruby environments, from interpreters to sets of Gems.” The following command takes care of the installation of the script. RVM will get installed in the home directory of the currently logged-in user.

1 $ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)

The RVM Logo

Navigate to the home directory, and edit the user bash profile. This ensures that the RVM script gets loaded every time the corresponding user logs in. To edit the bash profile, we’ll use Nano. Nano is a simple command-line text editor, and we will use it again in this tutorial.

1 $ cd
2 $ nano .bashrc

Add the following line to the end of the user bash profile. After you have made the changes, save the file by pressing CTRL + O, and exit Nano by pressing CTRL + X. If you ever want to exit Nano without saving changes, hit CTRL + X and then N.

1 [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

Manually load the script into the current shell session with the following command or open a new terminal window. This way, the rvm command will be made available.

1 $ source .bashrc

You can verify whether the RVM script is working by entering the following command:

1 $ type rvm | head -1

If everything is set up correctly, the shell should return that rvm is a function. If it doesn’t, go over to the RVM website and look under “Troubleshooting your install” to see what you can do to make it work.

Prepare Your Machine For Ruby And RubyGems

RVM comes with a handy command to view the dependencies that are needed to compile and install Ruby and RubyGems from source.

1 $ rvm notes

See the dependencies listed under the regular version of Ruby, and install these. Some packages might already be installed.

1 $ sudo apt-get install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev

Install Ruby And RubyGems Using RVM

First, we have Ruby, “a dynamic, open-source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.”

Then we have RubyGems. This is “the premier Ruby packaging system. It provides a standard format for distributing Ruby programs and libraries, an easy-to-use tool for managing the installation of Gem packages, a Gem server utility for serving Gems from any machine where RubyGems is installed, and a standard way of publishing Gem packages.”

The Ruby Logo

Like the RVM command described above, there is also a command to see what versions of Ruby are available for installation using RVM. Have a look at the available Ruby versions using this command:

1 $ rvm list known

Install a regular version of Ruby. Because Ruby gets compiled from source, this step might take a while.

1 $ rvm install 1.9.2

Start using the installed Ruby, and set this version as a default.

1 $ rvm --default use 1.9.2

Check the Ruby and RubyGems versions to see whether they have been properly installed.

1 $ ruby -v
2 $ gem -v

If necessary, manually updating RubyGems and the Gems is possible.

1 $ gem update --system
2 $ gem update

Install Rails Using RubyGems

Rails Gem itself is all that’s left for Ruby to be put on Rails. Installing this is one of the easiest parts of this tutorial. It is installed using RubyGems, invoked by the gem command. When the installation finishes, check the Rails version to see whether Rails has been properly installed.

1 $ gem install rails
2 $ rails -v

The Rails Logo

Install Capistrano Using RubyGems

Capistrano is “an open-source tool for running scripts on multiple servers. Its main use is deploying Web applications. It automates the process of making a new version of an application available on one or more Web servers, including supporting tasks such as changing databases.” You can install Capistrano using RubyGems. Check the Capistrano version to see whether it has been properly installed.

1 $ gem install capistrano
2 $ cap -V

Install PostgreSQL

PostgreSQL is “a sophisticated object-relational DBMS, supporting almost all SQL constructs, including subselects, transactions, and user-defined types and functions.” Install PostgreSQL together with a dependency. This dependency is needed to install the pg Gem later on, which is responsible for the connection between PostgreSQL and Ruby on Rails.

1 $ sudo apt-get install postgresql libpq-dev

The PostgreSQL Logo

Configure PostgreSQL

When the packages have been installed, move on to configuring PostgreSQL by securing pSQL. pSQL is the PostgreSQL interactive terminal, and it is used for administrative database tasks.

By default pSQL does not require a password for you to log in. We’ll change this by editing the authentication method and then reloading the PostgreSQL configuration. But first, assign a password to super-user postgres. Log into pSQL, assign a safe password to postgres, and then log out of pSQL.

1 $ sudo -u postgres psql
2 # \password postgres
3 # \q

Now modify the authentication configuration by changing ident to md5. This ensures that a password is needed to log into pSQL and that the password is encrypted. The two lines that need to be edited can be found near the end of the configuration file. After that, reload the changed configuration into PostgreSQL.

1 $ sudo nano /etc/postgresql/8.4/main/pg_hba.conf
2 $ sudo /etc/init.d/postgresql reload

Most other PostgreSQL settings are stored in another configuration file. These settings can also be optimized, but that is beyond the scope of this tutorial. Keep in mind that a reload of the PostgreSQL configuration is required in order for changes to become active.

1 $ sudo nano /etc/postgresql/8.4/main/postgresql.conf

The installation of the local development machine is now done.

Testing The Set-Up

To make sure everything works, let’s develop a really small application and see a bit of Ruby on Rails in action. This process covers the following steps:

  • Create a database user for the test application,
  • Create a database for the test application,
  • Create a test application using PostgreSQL as the database,
  • Install the necessary Gems for the test application,
  • Configure the database connections for the test application,
  • Generate a simple scaffold for the test application,
  • Migrate the results of the scaffold to the test application database,
  • Start the built-in server,
  • Check the test application in a Web browser,
  • Stop the built-in server.

Once we have verified that everything works, we go through the following steps:

  • Delete the database for the test application,
  • Delete the database user for the test application,
  • Remove the test application.

All of these steps should be performed on the local development machine. The conventions used to test the VPS are as follows (the database user name and database name derive from the name of the application):

Box 1.1

Name of application: test_app

Name of database user: test_app

Password of database user: apple

Name of database: test_app_development

First, create a database user for the test application using the createuser command. We are using postgres as the admin (or super-user) for PostgreSQL. The P flag allows us to provide a password. The > sign stands for the questions that will be prompted.

1 $ sudo -u postgres createuser -P
2 > Enter name of role to add: test_app
3 > Enter password for new role: apple
4 > Enter it again: apple
5 > Shall the new role be a superuser? (y/n) n
6 > Shall the new role be allowed to create databases? (y/n) n
7 > Shall the new role be allowed to create more new roles? (y/n) n
8 > Password: your-postgres-user-password

Then, create a database for the test application that is owned by the test application user. While we could use Rake to create a database, we will use PostgreSQL, so that we learn some basic PostgreSQL administration. Create a new database by invoking the createdb command in conjunction with the O flag, the database user name and the new database name itself. The addition of development at the end makes it the default database name. Here, you will be prompted for the PostgreSQL super-user password again.

1 $ sudo -u postgres createdb -O test_app test_app_development
2 > Password: your-postgres-user-password

Now that the database has been set up, it is time to create the actual Ruby on Rails application. Navigate to your home directory, and create a new Rails application, named test_app, using PostgreSQL as the database back end. The d flag allows us to specify the preferred database software.

1 $ cd
2 $ rails new test_app -d postgresql

Go into the Rails application directory, and install the necessary Gems using Bundler. Bundler takes care of “an application’s dependencies through its entire life across many machines systematically and repeatably,” and it “works out of the box with Rails 3.”

1 $ cd test_app
2 $ bundle install

Use Nano to edit the database configuration file by adding apple as a password under the development database configuration. Because we have followed convention, described in Box 1.1 above, the database user name and database name have already been taken care of.

1 $ nano config/database.yml

Now generate a basic scaffold. This will create a User model and a users controller. The inputs will consist of a name and an email address, which are both strings in the PostgreSQL database.

1 $ rails generate scaffold User name:string email:string

Use Rake to migrate the scaffold to the development database. Rake is an acronym for Ruby Make. It is a “simple Ruby build program with capabilities similar to Make,” which allows you to create and migrate databases.

1 $ rake db:migrate

By now, it is time to check the (working) application in a Web browser. Start the built-in server, and use a Web browser to navigate to http://localhost:3000/. In particular, look at the application’s environment, and then look athttp://localhost:3000/users. Create, edit, view and delete some users.

1 $ rails server

When everything appears to be working correctly, you can stop the built-in server.

1 $ press CTRL+C

If everything has worked, then the test application database and test application database user can be removed. Thedropdb command removes a PostgreSQL database.

1 $ sudo -u postgres dropdb test_app_development
2 > Password: your-postgres-user-password

The dropuser command removes a PostgreSQL user.

1 $ sudo -u postgres dropuser
2 > Enter name of role to drop: test_app
3 > Password: your-postgres-user-password

Finally, navigate to your home directory, and recursively remove the test application. This leaves you with a fresh local development machine, ready for developing Ruby on Rails applications.

1 $ cd
2 $ rm -r test_app

In part 2 of this tutorial, which will be published here later, we will help you through the steps necessary to set up an Ubuntu VPS that is capable of hosting (multiple) Ruby on Rails applications.

Linux Command Line Glossary

The relevant Linux commands for this tutorial are listed below in alphabetical order. A Linux command usually takes the form of command -option(s) argument(s). For example, rm -r test_app. For a more detailed description, use the manual pages, which can be accessed using man [command].

  • sudo [command]Used to execute a command as an administrative user.
  • apt-get dist-upgradeIn addition to performing the function of upgrade, this is used to intelligently handle dependencies.
  • apt-get install [package]Used to install (or upgrade) packages.
  • apt-get updateUsed to resynchronize the package index files from their sources.
  • apt-get upgradeUsed to install the newest versions of all packages currently installed.
  • bash < <( curl [location] )A combination of commands for obtaining and executing a script (from the Internet).
  • cd [location]Used to change the current working directory. Without an argument, it goes to the user’s home directory.
  • nano [file]Used to edit configuration files.
  • rebootUsed to reboot the system.
  • rm -r [directory]Used to remove a directory (recursively).
  • source [script]Used to force bash to read a specified script.
  • type [command]Used to display the kind of command that the shell will execute.

References

http://www.smashingmagazine.com