Wednesday, December 17, 2008

nil? problem on object methods in ruby use Object#try

Object#try is a solution that I like. However, it uses Object#respond_to?
Ruby Community uses this solution recently in github.
class Object
##
# @person ? @person.name : nil
# vs
# @person.try(:name)
def try(method)
send method if respond_to? method
end
end

But it does not solve the problem of args and blocks.
The right solution for generic try method is :
#By Jagan Reddy

class Object

def try(method, *args, &block)

send(method, *args, &block) if respond_to?(method, true)

end
end

difference between lambda and Proc.new (Closures)

The #lambda is not the same as Proc#new. It’s ok to say the same, but not exactly.
1: First Difference
$ irb irb(main):001:0>
Proc.new{|x,y| }.call 1,2,3
=>
nil


irb(main):002:0>
lambda {|x,y| }.call 1,2,3

ArgumentError: wrong number of arguments (3 for 2) from (irb):2 from (irb):2:in `call' from (irb):2 from :0
irb(main):003:0>

2: Second Difference
def test_ret_procnew
ret = Proc.new { return 'Returned' }
ret.call “This is not reached”
end
# prints 'Returned'
puts test_ret_procnew


While return from lambda acts more conventionally, returning to its caller:

def test_ret_lambda
ret = lambda { return “Returned” }
ret.call
“This is printed”
end
# prints “This is printed”

puts test_ret_lambda

Friday, December 12, 2008

Sass & Haml AutoCompile option

If you are using Sass & Haml, then you may wanted to compile files for each request =>

Just add the following small chunk of  code to your development.rb file.

Sass::Plugin.options[:always_update] = true
 
 

Wednesday, December 10, 2008

Ruby language features

When started learning ruby in 2004, api helped me to understand the features.
Though I used most of rugular expressions and classes, rails gave me enough experience to make use of
many ruby unique features like jayson expalined in the following article.

http://www.rubytips.org/2008/04/07/10-unique-ruby-language-features/

Also look athe Features of Ruby by Michael Neumann

http://www.ntecs.de/old-hp/s-direktnet/ruby_en.html

Friday, December 05, 2008

Ruby on Rails Rake Tutorial

In Rails developement, we will be using running "rake" to run your tests or maybe you've used "rake db:migrate" to run your migrations. Many of us know about Make scripts. What if you want to run ruby scrupts inside make then we need rake for that. Did you realize that you can write your own tasks or create your own library of useful Rake files?

Greg of rails envy gave nice article on Rails Rake ..:-)

http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial

Friday, November 07, 2008

APTANA ,RDT and RadRails Keyboard Shortcuts

RDT together with RadRails on Eclipse is a pretty convenient development environment when doing things in Ruby on Rails. The keyboard shortcuts.

Ctrl-Alt-T

Jump to the test case of a model or controller and vice versa.

Ctrl-Shift-V

Jump to the view of a controller method and vice versa.

Ctrl-Alt-X

Factor out a partial from a view. Simply select the code block you want to factor out into a separate partial an press the key combination. A window opens an you can enter the name for the new partial (dont't forget the _ and the .rhtml).

Ctrl-Shift-F

Auto-format the selected code (Ruby only). Not that mature, yet, and seems to have problems with regular expression - currently not recommended to use.

Ctrl-Shift-C

Toggle comment (Ruby only), i.e. the selected code block will be commented out if it wasn't (# are inserted in the first column of each row), and vice versa.

You can also keep up with general Aptana updates as well as RDT and RadRails specific news on the Aptana blog.

Aptana RadRails Debugger Problem

I've found the debugger equally slow when launching it via the "servers" tab.

There is a new "remote debug" capability in the trunk version of RadRails. Instead of launching a server from within RadRails, you can start your server externally (on the same or a different computer) under the control of debug-ide and then attach to it from a debug session in RadRails.

I've been using this capability, and found that it also solves the "slow debugger startup" problem.

Not sure why, and I wouldn't have expected it, but it's what I've observed.

Friday, October 10, 2008

Ruby on Rails applications with Mongrel cluster and Apache url rewriting on Windows

For windows, we need install mongrel_service gem to run mongrel clusters...

What you will need to do is to manually create n mongrel services for the n clusters you will need.

Visit this link . you will find windows mongrel configuration as well as ubuntu tooo

Nice article and simple tooo

Ruby on Rails applications with Mongrel cluster and Apache url rewriting on Windows

mongrel not running on windows

C:/ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
`gem_original_require': no such file to load -- C:/ruby/lib/ruby/gems/
1.8/gems/mongrel-1.1.2-x86-mswin32/lib/mongrel/init.rb
(MissingSourceFile)

I did 'gem update mongrel' and it said :

Successfully installed mongrel-1.1.5-x86-mswin32-60

I noticed the version of the one installed is later than the one in
the mongrel error message.  Is there an older version of something
that is causing this?
 
I solved this by the following way 
by changing the name of your
folder C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60  to
C:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.2-x86-mswin32 
and it should work as usual 

How to build Ruby On Rails projects using Hudson part -2

CI::Reporter is an add-on to Test::Unit and RSpec that allows you to generate XML reports of your test and/or spec runs. The resulting files can be read by a continuous integration system that understands Ant‘s JUnit report XML format, thus allowing your CI system to track test/spec successes and failures.

Installation

CI::Reporter is available as a gem. To install the gem, use the usual gem command:

    gem install ci_reporter

To use CI::Reporter as a Rails plugin, first install the gem, and then install the plugin as follows:

    script/plugin install http://svn.caldersphere.net/svn/main/plugins/ci_reporter

Usage

CI::Reporter works best with projects that use a Rakefile along with the standard Rake::TestTask or Spec::Rake::SpecTask tasks for running tests or examples, respectively. In this fashion, it hooks into Test::Unit or RSpec using environment variables recognized by these custom tasks to inject the CI::Reporter code into the test or spec runs. If you‘re using the Rails plugin, step 1 is unnecessary; skip to step 2.

  1. To use CI::Reporter, simply add the following lines to your Rakefile:
     require 'rubygems'
    gem 'ci_reporter'
    require 'ci/reporter/rake/rspec' # use this if you're using RSpec
    require 'ci/reporter/rake/test_unit' # use this if you're using Test::Unit
  2. Next, either modify your Rakefile to make the ci:setup:rspec or ci:setup:testunit task a dependency of your test tasks, or include them on the Rake command-line before the name of the task that runs the tests or specs.
     rake ci:setup:testunit test

Report files are written, by default, to the test/reports or spec/reports subdirectory of your project. If you wish to customize the location, simply set the environment variable CI_REPORTS (either in the environment, on the Rake command line, or in your Rakefile) to the location where they should go.


Source

You can get the CI::Reporter source using Git, in any of the following ways:

    git clone git://git.caldersphere.net/ci_reporter.git
git clone http://git.caldersphere.net/ci_reporter.git
git clone git://github.com/nicksieger/ci_reporter.git

How to build Ruby On Rails projects using Hudson





In this guide I'm going to show how to set up a Ruby on Rails project on the Continuous integration server Hudson. I've been using Hudson on Ruby on Rails projects since september and it works really well.



Initial downloads

The following files are needed besides Java (at least 1.5). Get the latest version of all files and notice that the Hudson file has the extension .war and plugins .hpi. This guide assumes that Ruby, Rake and Svnplugin are already installed and working.



* Hudson server application



* Ruby plugin



* Rake

Installation steps

I'm going to install Hudson into c:\Program Files\Hudson.

  1. Copy the hudson.war file to c:\Program Files\Hudson

  2. Start Hudson through "java -DHUDSON_HOME=data -jar hudson.war". Verify that you can access Hudson through http://localhost:8080

  3. Copy the plugins to c:\Program Files\Hudson\data\plugins

  4. Stop Hudson by pressing Ctrl+C in the command prompt where you started Hudson.

  5. Start Hudson again and you should be set to go.

Hudson system configuration

Follow the following steps to configure the tools that Hudson will use in building Your project.

  1. Go to the System configuration at http://localhost:8080/configure.

  1. Click the "New job" link at the home page.

  2. Enter the name "Your project", check the "Build a free-style software project" and press OK.





Source code management

Assumes thata ur project uses a Subversion SCM. Hudson supports CVS and SVN out of the box, but there are many plugins for other SCMs. After checking out the files from the repository Hudson will show the new change sets since the previous build in the Build page. A detailed view of change sets can be seen in the Changes page as the name of the developer, files that were changed and the comment for the change. Each change set is linked to the subversion repository browser, so it is easy to browse the actual file that changed.

  1. Press the Subversion radio button to configure the SCM.


  2. Repository URL=https://xxx.svn.sourceforge.net/svnroot/xxx/trunk/xxx

  3. Local module directory=.

  4. Press the Advanced button

  5. Repository Browser=ViewSVN, URL=http://xxx.svn.sourceforge.net/viewvc/xxx/



To test the configuration, press Save and then Build. The source code will be downloaded from the repository and put into the Workspace. If there were any changes in the SCM repository they can be viewed in the Changes page.





When the build is completed verify that it has checked out the code by going to the Workspace page. Using the Workspace page you can browse and view the files that has been checked out and it doesn't matter if the files are on the master or on a distributed slave!



When the plugin is avalable it detects your ruby instances installed from your PATH but it allows you to add other ruby or jruby paths:



Finally you just need to select the Invoke Rake option into the project configuration and select the tasks that you want to Hudson executes:



That's it, you are ready to go with Rake, Hudson and the Continuous Integration Game.

Tuesday, August 26, 2008

RESTful Rails in Short

What is REST?
coined by Roy Fielding stands for REpresentational State Transfer
describes an architecture for web apps centered around resources

REST constraints
  • client-server
  • stateless
  • cache
  • uniform interface
  • layered system
  • code-on-demand

REST data elements
  • resource
  • resource identifier
  • representation
  • representation metadata
  • resource metadata
  • control data

Rails resource

  • manipulated via HTTP methods
  • URL addressable entity
  • represented in different formats
Rails resource manipulations

operation SQL REST
create insert POST
read select GET
update update PUT
delete delete DELETE

Rails resource URLs

Traditional Rails RESTful Rails
POST /post/create POST /post
GET /post/show/1 GET /post/1
POST /post/update/1 PUT /post/1
POST /post/destroy/1 DELETE /post/1

Creating a resource
./script/generate scaffold_resource \
post \
title:string \
content:text \
created_at:datetime

creates
model, views, controller, helper
fixtures, unit tests, functional tests,
migration (fully functional!)
modifies
config/routes.rb

Model
app/models/post.rb
class Post < ActiveRecord::Base
end
nothing new!

View
app/views/posts/show.rhtml

Title:<%=h @post.title %>


Content:<%=h @post.content %>


Created at:<%=h @post.created_at %>


<%= link_to ‘Edit’, edit_post_path(@post) %> |
<%= link_to ‘Back’, posts_path %>
new syntax for link_to URLs!

Views: routes
config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.resources :posts
end
defines path methods and URL methods

Action `````HTTP request````````` Path method
index GET /posts projects_path
show GET /posts/1 project_path(1)
new GET /posts/new new_project_path
edit GET /posts/1;edit edit_project_path(1)
create POST /posts projects_path
update PUT /posts/1 project_path(1)
delete DELETE /posts/1 project_path(1)

new
form_for(:post, :url => post_path) ...
edit
form_for(:post, :url => post_path(@post), \
:html => {:method => :put}) ...
destroy
link_to ‘Destroy’, post_path(post), :method => :delete

Controller
app/controllers/posts_controller.rb
def destroy
@post = Post.find(params[:id])
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.xml { head :ok }
end
end
uses respond_to and post_url

Controller: routes

Traditional Rails
redirect_to :controller => ‘posts’, \
:action => ‘show’, :id => @post.id

RESTful Rails
redirect_to post_url(@post)
Each path method has equivalent URL method
Remember: use URL methods for redirect_to

Controller: respond_to
multiple representations of the resource
respond_to uses
accept HTTP-Header of the request
format appended to the request URL
register new formats in config/environment.rb
to extend responds_to
Mime::Type.register ‘image/png’, :png

Migration

db/migrate/001_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.column :title, :string
t.column :content, :text
t.column :created_at, :datetime
end
end

def self.down
drop_table :posts
end
end

Nested resources
strongly coupled resources
expressed in the URLs
creating a nested resource

./script/generate scaffold_resource comment \
post_id:integer created_at:datetime \
author:string content:text

models
models must be edited to express relationship

app/models/post.rb

class Post < ActiveRecord::Base
has_many :comments
end
app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
end

routes
routes must be edited to reflect relationship

config/routes.rb

map.resources :comments
becomes
map.resources :posts do |posts|
posts.resources :comments
end

Path method Path
comments_path(1) /posts/1/comments
comment_path(1, 2) /posts/1/comments/2
new_comment_path(1) /posts/1/comments/new
edit_comment_path(1) /posts/1/comments/2;edit

controller
nested resources controllers must be adapted
def index
post = Post.find(params[:post_id])
@comments = post.comments.find(:all)
...
end

REST benefits
  • clean URLS
  • multiple representations
  • less code
  • CRUD oriented controllers
  • clear application design
  • scalability

Friday, August 22, 2008

SQL Injection in Ruby On Rails

SQL Injection
One of the most common security holes in web applications is that they pass user input
directly to the database without quoting. Thus, a malicious user can fairly easily run all the SQL
he wants to on the server. An example of this would be a search form submission that is handled
by the following code:

@courses = Course.find(:conditions => "name = '#{params[:q]'")

Now let’s say JHON puts the following string into the search form:

"science'; delete from courses; --"

The resulting SQL query will be as follows:

SELECT * from courses where name = 'science'; delete from courses; --'

This is a perfectly valid SQL query and will effectively wipe out the whole courses table. Thus,
you should never, ever, pass anything unquoted to the :conditions parameter of ActiveRecord
finders. Instead, use the bind variable syntax:

@courses = Course.find(:conditions => ["name = ?", params[:q]])

You can pass in as many question mark/variable pairs you need. They will be parsed and
quoted in the order they are specified.

Another option in simple cases is to use the magic finders, where the parameter value is
automatically quoted, too:
@courses = Course.find_by_name(params[:q])

Tuesday, August 19, 2008

Dojo Button and Rails Helpers

Dojo Button and Rails Helpers

When i tried to use dojo buttons on rails partials , i felt happy about dojo widgets.

But if i have to use save_tag button or i want to include button in link_to_remote function,
I dont have option to get dojo style button.

I have used firebug to get the required dojo classes for dojo button and created following helper methods.

def dojo_button(name)
''
end
def dojo_button_class
"dijit dijitLeft dijitInline dijitStretch dijitButtonNode dijitButtonContents dijitButton"
end

save_tag to avoid multiple click in IE and Firefox

##############################################################################
# Overrides sumit_tag for disable save after click event --JAGAN REDDY
##############################################################################
def commit_tag(value,options={})
options.stringify_keys!
submit_tag value, options.merge(:onclick => '

if(window.addEventListener)
{
this.disabled = true;
}
else
{ // IE
var element = window.event.srcElement;
var tag = element.tagName.toLowerCase();
if(tag == "input")
{
var click = element.onclick;
var keypress = element.onkeypress;
setTimeout(function() { element.disabled = true; element.onclick = null; element.onkeypress = null; }, 0);
setTimeout(function() { element.disabled = false; element.onclick = click; element.onkeypress =keypress; }, 20000);
}
}
')
end
use this in apllication_helper.rb

Wednesday, July 23, 2008

Ruby: Floating point round off

my method of doing this as

def round(float, decimal_places) # By Jagan Reddy
exponent = decimal_places + 2
@float = float*(10**exponent)
@float = @float.round
@float = @float / (10.0**exponent)
end

In short we can also do this way
class Float
def round_to(i)
(self * 10**i).round.to_f / 10**i
end
end
value = 1328.3337
value.round_to(3)
=>1328.334

Friday, July 11, 2008

New AJAX google api rails plugin coming soon

Check this link for sample google ajax rails helper modules ...

http://www.strictlyuntyped.com/2008/06/using-google-ajax-libraries-api-with.html

Error can't dump anonymous class Class (apatana studio)

The system has a mainDocument model with different subclasses for different types of documents.
With the code below, if I attempt to create a Document, it works fine, but
if I attempt to use one of the subclasses, I get the error:

can't dump anonymous class Class

With an Application Trace of:

C:/Ruby/lib/ruby/1.8/yaml/rubytypes.rb:6:in `to_yaml'

When i started using aptana studio (radrails) 1.1.6 etc.. i got this error.

I searched all over the net for rails or ruby error list for this kind.. i could not find this problem any where.

But it solved when stopped apatana from dubugging mode to regular mode.

I dont know why but it works me fine afterwards.


please put your comments if u find any other soultion


Wednesday, May 21, 2008

What is Rubinius ?

Evan Phoenix's Rubinius project is an effort to implement Ruby using as much Ruby code as possible. It is not, as professed, "Ruby in Ruby" anymore. Rubinius started out as a 100% Ruby implementation of Ruby that bootstrapped and ran on top of MatzRuby. Over time, though the "Ruby in Ruby" moniker has stuck, Rubinius has become more or less half C and half Ruby. It boasts a stackless bytecode-based VM (compare with Ruby 1.9, which does use the C stack), a "better" generational, compacting garbage collector, and a good bit more Ruby code in the core libraries, making several of the core methods easier to understand, maintain, and implement in the first place.

The promise of Rubinius is pretty large. If it can be made compatible, and made to run fast, it might represent a better Ruby VM than YARV. Because a fair portion of Rubinius is actually implemented in Ruby, being able to run Ruby code fast would mean all code runs faster. And the improved GC would solve some of the scaling issues Ruby 1.8 and Ruby 1.9 will face.

Rubinius also brings some other innovations. The one most likely to see general visibility is Rubinius's Multiple-VM API. JRuby has supported MVM from the beginning, since a JRuby runtime is "just another Java object". But Evan has built simple MVM support in Rubinius and put a pretty nice API on it. That API is the one we're currently looking at improving and making standard for user-land MVM in JRuby and Ruby 1.9. Rubinius has also shown that taking a somewhat more Smalltalk-like approach to Ruby implementation is feasible.

Rails on Virtual Machine

There was a short note today, that the Rubinius development team has successfully run Rails on their virtual machine. Although isn’t anywhere new production ready yet, it is a significant step forward in getting a faster Rails.

I covered some of the alternate Ruby implementations previously.

Congratulations to the team!

Rails Development Tips part-2

  • Use database indexes to speed up queries. Rails only indexes primary keys, so you’ll have to find the spots that need more attention.
  • Profile your code. The ruby-prof gem and plugin helped me make an application three times faster with only minimal changes to the code.
  • Minimize graphic-related dependencies. If your application only needs to make a few thumbnails, don’t waste memory by importing large graphics libraries. Look at mini-magick or image_science for lightweight thumbnailing.
  • Avoid excessive repeated rendering of small partials.
  • Use CSS instead of inline tags to apply selective styling.
  • Don’t use ActiveRecord’s serialize option to store large objects in database fields.
  • Use attr_protected :fieldname in models to keep database fields from being manipulated from forms (or from any calls to Model.update_attributes(params[:model])).
  • Use Ruby classes and inheritance to refactor repeated controller code.
  • Use unobtrusive Javascripting techniques to separate behavior from markup.
  • Package self-sufficient classes and modules as plugins or RubyGems.
  • Cache frequently accessed data and rendered content where possible.
  • Write custom Test::Unit assertions or rSpec matchers to help with debugging test suite errors.
  • Rotate the Rails and Mongrel logfiles using the logrotate daemon on Linux.
  • Build a reliable backup system.
  • Automate deployment and maintenance with Capistrano or Vlad.
  • Keep method bodies short. If a method is more than 10 lines long, it’s time to break it down and refactor.
  • Run flog to determine overly complex methods and clases.
  • Don’t use too many conditionals. Take advantage of case statements and Ruby objects to filter instead of multiply-nested if statements.
  • Don’t be too clever. Ruby has great metaprogramming features, but they are easy to overuse (such as eval and method_missing).
  • Become familiar with the most popular plugins. Instead of re-implementing the wheel, save yourself some time by using well tested, popular plugins
source :http://nubyonrails.com/articles/massive-list-of-rails-development-tips

Rails Development Tips or Hints part 1

  • Store sessions in the database (or at least not on disk, which is the default).
  • Use a custom configuration file for passwords and API keys instead of storing them in your Subversion repository. I use YAML and mirror the style of database.yml.
  • Use constants where needed. Instead of repeating strings like the address of your customer service reply email, set it once in a constant (in environment.rb or the appropriate environment file) and use that throughout your application.
  • Keep time in UTC. A no brainer, and easy to do.
  • Don’t loop through ActiveRecord models inside other models. Use eager loading if you need to work with multiple associated models. Better yet, write a custom SQL query and let the database do the work for you.
  • Beware of binary fields. By default, all fields are returned with queries, including the full contents of any binary fields. Use :select to pull out only the fields you need.
  • Write tables to cache data for reports that span months and years. It’s much faster than re-generating a year’s worth of reports every time a page is loaded.
  • Create a table with a list of country names. By default, Rails uses strings for selects and lists of countries, which doesn’t work well for reporting or database consistency between models.
  • Avoid bloated controllers. Instead of piling actions into a controller, limit yourself to 10 actions per controller, then rethink your design.
  • Keep your controllers and views skinny. In general, most of your code should be in your models, not your controllers or views.
  • Don’t store objects in the session. Use integers or short strings if necessary, then pull the appropriate object out of the database for the duration of a single request.
  • Avoid heavy response processing. Can you mark a record as needing to be processed, then use a cron job or a messaging server to do the long-running work? BackgroundRB is also an option. (I use this technique for filtering SPAM comments on this blog).
  • Use ar_mailer to queue bulk emails instead of sending them during the Rails response cycle.
  • Monitor your servers with the exception_notification plugin, munin, monit, or other tools.
  • Don’t cut costs on hardware. You’ll quickly lose the money you thought you were saving if your developers have to spend even one day a month on unexpected server maintenance due to poor backups or cheap hardware.
  • Test-drive your development.