Poetry of Programming

Its about Ruby on Rails – Kiran Soumya

By

SSL/HTTPS on Devise + Rails3

I have seen gems like ssl_requirement, but its too complicated for securing just two pages of user login and sign up.

Referred few blogs and found few useful links for the same:

1> For
# Creating your private key
# Creating your certificate signing request
# Getting your certificate
# Configuring your web server
Refer: http://www.buildingwebapps.com/articles/79189-using-ssl-in-rails-applications
2> For Setting up Rails app with Devise, I have referred this :
http://blog.grow20.com/fun-with-ssl-for-accounts-only

More useful links:
http://blog.dynamic50.com/2011/02/15/ssl-on-wildcard-domains-on-heroku-using-godaddy/
http://www.themomorohoax.com/2010/10/08/using-ssl-in-rails-3

By

Rake Task in Rails 3 on Production ENV

Cannot execute Rake Task in production environment? Does it throws errors of uninitialized objects or refuses to load Model classes?

To execute a rake task for eager loading we require,
config.threadsafe! to be disabled in production which is enabled by default.

But our requirement is to get it disabled only on running a rake task.

Rake already sets a Ruby global: $rails_rake_task

So, in config/environments/production.rb, just say:

 config.threadsafe! unless $rails_rake_task

By

Installing RVM & Git through Proxy

RVM relies on GIT.

So set proxy for GIT first.

*  Set the http_proxy environment
*  Set a proxy command to bypass the connection:
gcc -o connect connect.c
mv connect ~/bin
echo “/home/kiran/bin/connect -H proxy.company.com:6030 $@” >> ~/bin/proxy
chmod +x ~/bin/proxy

echo “export GIT_PROXY_COMMAND=proxy” >> .bashrc

Now try git clone. If it doesnt work, try out the following the command.

export http_proxy=http://<username>:<password>@<proxy_ip>:<proxy_port>

This line below also works like a charm for GIT,

git config --global http.proxy proxy_addr:proxy_port

Once the GIT is configured, for RVM, you need to do one more change for curl,
Set the proxy inside your ~/.curlrc

proxy = proxy.company.com:proxy_port

and now you can install rvm with no issues.

For rvm install thru proxy:

rvm install X --proxy proxy.company.com:proxy_port

If two developers are under the same user-group, we can even clone/copy the .rvm folder within two users without explicit installations.

Some more references:
http://blog.iwkse.homeunix.org/index.php?/archives/9-Git-Basic-setup.html
http://beginrescueend.com/
http://zipizap.wordpress.com/2010/11/02/cloning-rvm-to-other-user-you-can-just-copy-the-rvm-directory/ [This worked for me as well]

By

Rails Passenger and PHPmyadmin Issue

After getting passenger up and running successfully on my machine and after many days of work, I have got to install PHPmyadmin. But Rails Passenger doesnt allow the connection to http://localhost/phpmyadmin.

After lot of search, I have got it fixed when I updated the following under httpd.conf:

<LocationMatch “^/phpmyadmin/.+”>
PassengerEnabled off
AllowOverride All
</LocationMatch>
Alias /phpmyadmin “/path/to/phpmyadmin”
<Directory “/path/to/phpmyadmin”>
PassengerEnabled off
AllowOverride All
</Directory>

This works like a charm…

By

Rails 2.3.3 Released

new release of Rails is available – Rails 2.3.3.Among the usual bug fixes, a few new features were added, from the release notes:

  • touch is a convenient method to update a record’s timestamp and nothing else. This is extracted from apps whose models “touch‚” others when they change, such as a comment updating the parent.replies_changed_at timestamp after save and destroy.[..]
  • :primary_key option for belongs_to for broader support of legacy schemas and those using a separate UUID primary key: belongs_to :employee, :primary_key => ‘SSN’, :foreign_key => ‘EMPID’ [..]
  • leaner user-facing encoding [JSON] API.
  • decoding backends for the json and yajl libraries. Both are significantly faster than the default YAML backend.

Meanwhile, the work on Rails 3 continues. Yehuda Katz has posted a few blog entries on the new architecture for Rails 3, as well as lessons learned from refactoring a large code base as Rails.One of the goals of Rails 3 is to bring Merb’s modularity and well defined internal APIs to the Rails codebase; Yehuda’s article on the interface between ActionController and ActionView gives some insight in what’s going on on that front. What becomes clear is that the fusion of Merb and Rails is a major project and is still underway.The work on Rails 3 also has an impact on the development of Merb. A recent discussion on the Merb mailing list addressed the state of Merb 1.1, which was due a few months ago. The current plan is to make sure a smooth migration path to Rails 3 is possible – which, of course, requires to know what Rails 3 architecture will be.With all that said, Merb is still a viable solution for many projects, as Ezra Zygmuntowicz (Merb’s creator) points out:

I’d like to chime in and say that I am still happily building apps with merb, http://engineyard.com/solo is built on merb. I don’t find that there is anything I’m missing or that there are any features or major bugs stopping me from building apps with merb.

For another glimpse at plans for Rails 3, David Heinemeier Hansson’s RailsConf’09 talk is available online.

 

By

Driver Error: Svn Merge

The ‘svn merge’ command compares two trees, generates a patch, then
applies that patch to a working copy. Yes, you have complete freedom
to compare any two trees, and thereby generate any patch you want. But
that does *not* mean that ‘svn merge’ always will do what you want.
It’s *your* responsbility to make sure that the patch being produced
makes sense, and cleanly applies to your working copy.      
Skipped ‘src’
Skipped ‘src’
Skipped ‘src\au’
Skipped ‘src\au\com’
Skipped ‘src\au\com\forward’
Skipped ‘src\au\com\forward\codeSections’
A src\au\com\forward\codeSections\DesignNotes.txt
A src\au\com\forward\codeSections\CodeSections.java
Skipped ‘src\au\com\forward\codeSections\testFiles’
A src\au\com\forward\codeSections\testFiles\testin.cs
Skipped ‘docs’
Skipped ‘docs’
A docs\htmldoc.exe 

See those skipped messages? That indicates driver error. The merge
command is trying to add and remove certain directories because they’re
not related to each other at all. Please read this section of chapter
4, regarding ancestry:

http://svnbook.red-bean.com/en/1.1/ch04s03.html#svn-ch-4-sect-3.2.4

Then after reverting, try the merge again with the –ignore-ancestry
command.

So, It is like this what I have implemented,

> Taken a latest production copy as my_working_copy

> Merged the dev branch with production branch under  my_working_copy

svn merge –ignore-ancestry prod_branch_url dev_branch_url my_working_copy/

> And this is how we avoid the driver error.

> Check for conflicts under my_working_copy

Fix the conflicts always in favour of Clients Requirements.

Else if no conflicts, check in the merge to production

Finally, Say The END to the project !!!

Next is What ?  [ Samsung Adv :) ]

By

I need an individual file to be migrated in Rails

Rails migrations are great, they allow continual evolution of database schema. Sometimes, especially when prototyping, I hate to run migrations down and up and load data, just to make small independent change in database table. In this situations I run only specific migration:

ruby script/runner 'require "db/migrate/005_create_blogs"; \n
CreateBlogs.migrate(:down)'
ruby script/runner 'require "db/migrate/005_create_blogs";\n
 CreateBlogs.migrate(:up)'

This is much typing (for just one migration at least 😉 so here is the rake task to do the same:

namespace :db do
  task :migrate_one => :environment do
    file = Dir["db/migrate/#{ENV["VERSION"]}_*.rb"].first
    require(file)
    migration_class = file.scan(
/([0-9]+)_([_a-z0-9]*).rb/)[0][1].camelize.constantize
    migration_class.migrate(:down) unless ENV["DIRECTION"] == 'up'
    migration_class.migrate(:up) unless ENV["DIRECTION"] == 'down'
  end
end

Put this rake task in lib/tasks and you can call it with rake db:migrate_one VERSION=005. This would run migration down and up. You can also add DIRECTION=up or DIRECTION=down to control direction.

Thanks to Bojan Mihelac.

By

Ubuntu + ROR + Mysql + Svn +VPN

Every time we install Ruby/Rails/Mysql/Rmagick/Vpn on Ubuntu Gutsy or Hardy we face the same  errors again and again. Lets reduce the installation time and have a loop-back-fix-free or smooth installation experience.

After you run the CD or install Ubuntu, make sure of your Network Proxies if any, if so, you need to add the proxy url at System->preferences->Network Proxy.

then from terminal, make sure this passes…

sudo apt-get update

then for Mysql/Rails installation follow this:

http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-mysql-and-ror

and for VPN installation/connection on Ubuntu, this is the best guide:

http://www.cs.umn.edu/help/offsite/vpn.php#ubuntu_config

By

ROR : Important Points to be noted

> Difference between Ruby load and require:

Ruby programs may be broken up into multiple files, and the most natural way to partition a program is to place each nontrivial class or module into a separate file. These separate files can then be reassembled into a single program (and, if well-designed, can be reused by other programs) using require or load. These are global functions defined in Kernel, but are used like language keywords. The same require method is also used for loading files from the standard library.

load and require serve similar purposes, though require is much more commonly used than load. Both functions can load and execute a specified file of Ruby source code. If the file to load is specified with an absolute path, or is relative to ~ (the user’s home directory), then that specific file is loaded. Usually, however, the file is specified as a relative path, and load and require search for it relative to the directories of Ruby’s load path (details on the load path appear below).

Despite these overall similarities, there are important differences between load and require:

  • In addition to loading source code, require can also load binary extensions to Ruby. Binary extensions are, of course, implementation-dependent, but in C-based implementations, they typically take the form of shared library files with extensions like .so or .dll.

  • load expects a complete filename including an extension. require is usually passed a library name, with no extension, rather than a filename. In that case, it searches for a file that has the library name as its base name and an appropriate source or native library extension. If a directory contains both an .rb source file and a binary extension file, require will load the source file instead of the binary file.

  • load can load the same file multiple times. require tries to prevent multiple loads of the same file. (require can be fooled, however, if you use two different, but equivalent, paths to the same library file. In Ruby 1.9, require expands relative paths to absolute paths, which makes it somewhat harder to fool.) require keeps track of the files that have been loaded by appending them to the global array $" (also known as $LOADED_FEATURES). load does not do this.

  • load loads the specified file at the current $SAFE level. require loads the specified library with $SAFE set to 0, even if the code that called require has a higher value for that variable.

> To revert migrations to different version:

rake db:migrate version=19

> Task to delete all migration during deployment:

The delete command is just a convenience for executing rm via run. It just attempts to do an rm -f (note the -f! Use with caution!) on the remote server(s), for the named file. To do a recursive delete, pass :recursive => true:

Demonstrating delete [ruby]

delete #{release_path}/db/migrate“, :recursive => true

 

 

By

Difference between Mocks and Stubs

  • Many developers confuse the ideas behind stubbing and mocking. Stubbing simply replaces a real-world implementation with a simpler implementation. A stub can replace full login system with a simple substitute. A stub’s job is to simulate the real world. Mocks are not stubs. A mock object, instead, is like a gauge that measures the way your application uses an interface.
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it ‘sent’, or maybe only how many messages it ‘sent’.
  • Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Rspec Definitions for Mock and Stubs:Mocks are objects that allow you to set and verify expectations. They are very useful for specifying how the subject of the spec interacts with its collaborators. This approach is widely known as “interaction testing”.Mocks are also very powerful (though less widely understood) as a design tool. As you are driving the implementation of a given class, Mocks provide an amorphous collaborator that can change in behaviour as quickly as you can write an expectation in your spec. These changes are tantamount to designing the interface to a collaborator that often does not yet exist. As the shape of the class being specified becomes more clear, so do the requirements for its collaborators – often leading to the discovery of new types that are needed in your system.
Stubs are objects that allow you to set “stub” responses to messages. Stubs provide canned responses to messages they might receive in a test, while mocks allow you to specify and, subsquently, verify that certain messages should be received during the execution of a test.

By

Single Table Inheritance

Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

  class Company < ActiveRecord::Base; end
  class Firm < Company; end
  class Client < Company; end
  class PriorityClient < Client; end

When you do Firm.create(:name => “37signals”), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.find(:first, “name = ‘37signals’”) and it will return a Firm object.

If you don‘t have a type column defined in your table, single-table inheritance won‘t be triggered. In that case, it‘ll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

Note, all the attributes for all the cases are kept in the same table. Another example is as follows:

STI
Relational databases don’t support inheritance, so when mapping from objects to databases we have to consider how to represent our nice inheritance struc-tures in relational tables. When mapping to a relational database, we try to minimize the joins that can quickly mount up when processing an inheritance structure in multiple tables. Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.


By

History of Ruby on Rails

Many web-based software systems contain a number of common types of components and functionality.
Calling application code based on HTTP posts, performing database transactions, rendering HTML
responses, and putting all of the system’s functionality into a scalable, extensible architecture are all common concerns in these applications. Because of the prevalence of web applications in today’s world, these problems are faced by many developers worldwide on a daily basis. Clearly, when facing such a task, a prudent software engineer would seek a common framework for web application development that could reduce the need to reinvent existing solutions, create a common base architecture for a number of different applications, and provide a ready-to-go solution for as many of the requirements as possible.

This solution to the problem is not a new one. Frameworks like Microsoft’s .NET or Sun’s Java 2
Enterprise Edition (J2EE) are widely used to satisfy the needs of developers creating large scale service
oriented architectures for web deployment. These systems have been tried and tested many times and are well known for the robust solutions they can provide. Unfortunately, with such a robust architecture seems to come an inherently large amount of overhead in terms of configuration and setup. In addition, there tends to be a large learning curve to understand the architecture and all of its variants. In particular, J2EE has many different technologies that can be glued together within it, including Struts, Hibernate, and Spring.

Enter Ruby on Rails. Ruby on Rails is an open-source web application framework designed to make the
job of the developer easier by providing everything one needs to create web-based, database-driven
applications easily while focusing on the idea, not the technology behind implementing the idea. It is
designed to be a marriage of the “quick-n-dirty” camp of PHP web developers and the “slow-n-clean”
methodologies of the old enterprise architecture crowd. Many proponents of the framework will be quick to tout quotes saying that it can make developing web systems ten times faster than performing similar tasks with competing, more complex frameworks like J2EE.

Rails was developed while its creators were building a real life system with it. This allowed them to test
out their ideas as they were putting them in to production, along with allowing them to drive the
development of the framework based on the actual needs of a real project.

The creator of Ruby on Rails, David Heinemeier Hansson of 37signals, will tell you that some of the
framework’s power comes from the fact that it follows the mantra of “convention over configuration.”
This means that instead of allowing an ultimate amount of flexibility in what a developer can do with a system, there are limits imposed. While this may sound like a bad thing, it actually allows for a much
easier time in creating the types of solutions that it is specifically designed for. In David’s words, “If you
are happy to work along the golden path that I’ve embedded in Rails, you gain an immense reward in
terms of productivity that allows you to do more, sooner, and better at the application level.” Basically,
because assumptions are made on the part of the framework about how the developer will be doing things, the developer doesn’t have to tell the framework how those things will be done. This means less time spent writing configuration files and more time working on the idea of the product.

A high-level view of the Rails architecture makes it look very much like other web application
frameworks. Its architecture is based on MVC, designed to separate concerns and reduce the coupling
between disparate functionality. Part of Rails’ power comes from the fact that this architecture is
connected through an auto-generated code base structure. The developer can set up a project and then
make changes to the model directly and observe the results without a lot of work to set up every part of
getting that data propagated throughout the rest of the system.

The entire benefit of using Ruby on Rails is in many of the small things it does to benefit the developer in
ways that other similar frameworks do not. These little things collectively work together to create a
development experience which overall seems much more agile and less cumbersome than the process
involved in working with other large and robust web development architectures.

In mid-2003, a small web development firm called 37signals was starting development on Basecamp, a
web-based project management tool. For several years, they had been using PHP for their applications
and trying to build up a reusable framework.
Unfortunately, their PHP framework failed to provide maximum productivity, and the programmers were
growing increasingly frustrated with their development experiences. PHP offered a quick and dirty approach to web applications, but 37signals was rapidly pushing the limits of what PHP reasonably
accomplish. On the other end of the spectrum, J2EE offered a slow and clean approach. The approach
was too slow, however, and unreasonably complex. In order to combine the best of both worlds into a
quick and clean approach, a new framework was needed. This framework would facilitate rapid
development with a focus on producing results, while also incorporating design patterns and best
practices.

Basecamp would be 37signals’ first product offering, and the project marked their transition from
consulting to product development. It was clear that if the company wanted to deliver an effective
product line without significantly expanding their resources, they would need a software platform to build on.

As a result, two primary goals emerged. First, 37signals needed an extensible, modifiable web
application framework that could be used to create Basecamp and future products. The framework would
promote code reuse and provide libraries of common functionality. Second, the framework itself needed
to make development enjoyable for the programmers, making the programmers extremely productive.
With increased productivity, 37signals could accomplish more work without hiring more developers.

To achieve the second goal and provide a starting point, Ruby was chosen as the programming language
for the web framework. The dynamic, powerfully expressive nature of Ruby along with its extensive
metaprogramming features ensured an enjoyable, fruitful development experience with plenty of
flexibility. By designing the framework to take advantage of Ruby’s unique traits, a clean productive
development was guaranteed.

Since Ruby was selected and established as a foundation, David could then address his first goal of
creating an extensible web framework. However, he did not build the framework upfront. Instead, he
proceeded to build Basecamp, and the framework that grew out of Basecamp became Ruby on Rails.
Unlike web frameworks like J2EE and .NET, which were developed to specifications designed to suit the
needs of all possible users, Ruby on Rails was extracted from a complete product. As a result, the
framework reflects the real needs of a real project, and contains no extraneous or unnecessary features for the average developer. Thus, when developing a future 37signals product, David could reuse Rails,
without being hindered by unnecessary components, and spend most of his time focusing on application
specific functionality.

Despite the fact that Rails began as a proprietary framework, a decision was made to avoid including
business logic and application-specific features. Originally, the scope was constrained simply to make the framework manageable and to guard against feature creep. When Rails was publicly released as open source, the lack of business logic left the framework as a powerful, general solution that the majority of programmers could reuse.

From its inception, the Rails framework has been driven by pragmatic, minimalist decisions. It uses
proven techniques from real-world applications, meaning that the framework is a reflection of the way
programmers actually work.

By

Best Article in November,2006!

Today I happened to visit a good article, David H. Hansson on the Future of Rails, where the InfoQ editor asks David about the future of rails in enterprises, the scalability and comparision of Java with Rails.

His interview teaches every developer how to really proceed to a project. Implement all ideas without really worrying about performance/scalability. This is like “Concentrate on Application but not bugs at first!” Then sort out pointing exactly where is the bottleneck? Then get that solved… coz every problem has solution.(Nothing is impossible)

By

Web 2.0 on Rocket Fuel

Ruby on Rails 1.1 is described as Web 2.0 on Rocket Fuel.

The much-anticipated new version 1.1 of Ruby on Rails hit the streets with fanfare a couple of days ago. And while even I am wary of the hyperbole that sometimes surrounds Ajax and Web 2.0, I’m very pleased to say that Ruby on Rails is the genuine article. Rails has become one of the real success stories in Web development in just the last year. Built by 37signals’ charismatic David Heinemeier Hanson and a host of contributors, Ruby on Rails has ascended to near-mainstream status nearly overnight.

For those of you not familar with Ruby on Rails, and a lot of you won’t be or have just barely heard of it, Ruby on Rails is a complete, open, and free application stack based on the Ruby programming language . This means it provides a complete solution for creating great online Ajax-based software of the kind that’s pouring out on the Web these days . Rails includes advanced Ajax support, Web services, an amazingly taut and clean model-view-controller implementation, and automatic object-relational mapping. Rails even includes seamless script.aculo.us and Prototype integration, as well as support for just about any database you will need.

Ruby itself is one of the interesting stores in software development lately because it’s a dynamic language, meaning that it isn’t compiled and is somewhat more akin to Perl and Javascript than a traditional hardcore language like Java or C++ . But that’s where similaries to Javascript end since Ruby is an elegant object-oriented language designed to make programming easy and make routine software development tasks almost effortless. In fact, when I did my C#, Java, and Ruby Web services development comparison last year, Ruby won hands down in development time, compactness, and generated by far the most readable code, even though it was the very first time I’d used it.
Ruby on Rails 1.1

Rails is a natural extension of these concepts in that it adds a framework to Ruby to make it maximally easy to build Web-based online software, with the single-minded intent of pushing complexity out to the edge cases. To get a sense of how powerful Ruby is, my recent discussion (video here) with David Heinemeier Hannson at Real-World Ajax revealed that 37signals not only built their 5 world-class online applications purely with Ruby on Rails, but they support almost 400,000 users on just 13 servers.

Dion Hinchcliffe and David Heineimeier Hansson discuss Ruby on Rails 1.1But there are dozens and dozens of Web development products out there, many of them very good, so what makes Ruby on Rails so special? One is that the Rails’ design focuses on trying to make the common Web development tasks fall-down-the-stairs easy, and it invariably succeeds. Like the Rails home page says, “Ruby on Rails is an open source Web framework that’s optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.” Rails proponents are reknowned for their plain spokeness and directness and the result of this attitude is clear throughout the framework.

Another real advance in Rails is the fact that it considerably reduces something called abstraction impedance. Abstraction impedance is a fancy $20 phrase that describes the barrier that exists when crossing from one way of thinking to another. Say the barrier of going from objects to databases, or Javascript to Ruby. Abstraction impedance is a productivity killer that sucks up programmer time doing things that don’t matter to what the application does. So instead of providing solutions to your users, you’re spending time converting information from one form to another. Rails makes this go away by giving the programmer plain old objects to deal with, no matter if you’re dealing with XML, relational database data, and now even Javascript in the browser.

This takes us to the new features in Ruby on Rails. As its biggest new feature, version 1.1 actually allows you to write your browser-side Javascript in Ruby. Javascript is a notoriously finicky language that doesn’t make it easy to create sophisticated Ajax appliations and that’s why IDEs, frameworks, and tools are springing up everywhere to make it simpler. Now Rails has just dropped one more complexity out of the process of building Web 2.0 software applications with RJS, the Ruby to Javascript compiler.

Web 2.0 software development has its own set of expectations and best practices: rapid feature evolution, real-time feature monitoring, all functionality available in both the GUI and as Web services so others can use them in their own apps, and more. Rails makes all of these easy to do using one of the highest productivity languages out there. That’s not to say Rails is perfect, it’s so new it couldn’t possibly be fault-free, but there is clear evidence today of its reliability, scalability and ease-of-use (once you get past a brief learning curve.)

What’s New In Rails: (complete list here)

  • RJS – Write your Ajax application’s Javascript in Ruby
  • ActiveRecord++ – Rails’ ActiveRecord is a powerful, automatic Object/Relational Mapping tool. It gets a major steroid boost in Rails 1.1.
  • API Support – Adding an API for your Web 2.0 software is now even easier
  • New Integration Tests – Rails understands testing and adds even more automatic test support
  • Backwards Compatibility – Even with 500 new changes, old Rails apps will almost universally run in Rails 1.1

If you’re interested in picking up Ruby on Rails, here are twelve excellent tutorials (http://www.digitalmediaminute.com/article/1816/top-ruby-on-rails-tutorials) that can get you started. And finally, if you haven’t bought all of this yet, take a look at this screencast. It shows step-by-step how to develop a working blog application in Rails from scratch in just 15 minutes, complete with comments and an administration interface. That’s the power of Rails, it really does let you focus on delivering great online software and not get mired in details that don’t matter. In any case, Rails is so new it has almost no enterprise penetration. But as the next generation of programmers uses it more and more, expect that to change, along with the way enterprises develop with Web technology.

By

Why Ruby on Rails?

The stack on the left is the Java books, the stack on the right is the Ruby books. The same breadth of material is covered. Well almost, there are on-line references for things like XSL, not covered in the Ruby books. But other than that the functionality is the same. So which stack will be easier to keep in my head? The choice is easy.

Check this url: http://www.garbett.org/?q=node/25#comment-13
Shawn gave a great comparision of Rails with Java.