Wednesday, January 30, 2008

What happened to nbrubyide daily build?

What happened to daily build of nbrubyide? I have been checking the last few days and there is no new build. I am so used to getting my morning nbrubyide fix. This is not a complain. I am just wondering.

Here is where I go to download the latest build.
http://deadlock.netbeans.org/hudson/job/ruby/changes

Thursday, January 17, 2008

Converts a comma separated string of numbers into an array of integers

This is all there is to convert a string of comma separated integers to an array of integers.

>> "1,24,53,6,23,6,5".split(",").collect{ |s| s.to_i }
=> [1, 24, 53, 6, 23, 6, 5]

This is why Ruby is so fun to use. Is there a shorter way to do this than what I have?

Tuesday, January 08, 2008

Expose Module methods as Instance and Class methods

Have you ever wondered how to include a Module and has its methods be available as instance methods and class methods? I certainly did and after doing a little research I figured out a way to do this in Ruby. For the experience Ruby programmers out there, this is probably very obvious but for those that haven't completely figured out Class object and instance of a class then this should help a little. Or totally confused you.

I don't know whether it is wise to do this but at least it is possible to do. Anyway, enough talking. Here is the code in all it (not so) glory.

module Methods
def self.included(base)
# add methods in ClassMethods into the meta class
base.extend(ClassMethods)
end

def hi
# accessing the meta class to call the
# real method
class << self
self.hi
end
end

def bye
class << self
self.bye
end
end

module ClassMethods
def hi
puts "Hello"
end

def bye
puts "Good Bye"
end
end
end

class Greeting
include Methods
end

# Calling Instance methods here
Greeting.new().hi
Greeting.new().bye

# calling Class methods here
Greeting.hi
Greeting.bye

Saturday, January 05, 2008

Encryption Data in Ruby using OpenSSL

I had been searching the web for a way to encrypt some data for my Rails project for a while and I finally found something that I could use. Encrypting Sensitive Data with Ruby (on Rails) has straight forward instructions on how to encrypt and decrypt data using OpenSSL in Ruby.

Friday, January 04, 2008

adding special helpers

I was cleaning up my view and decided that I want to add two helpers, display_if and display_unless to help clean up the view.

Instead of doing:

<% if @login %>
Hello <%= @user_name -%>.
<% end %>

It would be like this:

<% display_if @login %>
Hello <%= @user_name -%>.
<% end %>

I came from the Asp.Net world so writing a custom control to do this is not easy. I was expecting it to be difficult in Rails also but it turned out to be very simple.

It took me less than 10 minutes to figure it out from not knowing how to do it at all. Hopefully, I am doing it correctly.
Here is the code for the two helpers. Just put them in your application_helper.rb file.

def display_if(condition, &block)
raise ArgumentError, "Missing block" unless block_given?

if condition
output = capture(&block)
concat(output, block.binding)
end
end
def display_unless(condition, &block)
raise ArgumentError, "Missing block" unless block_given?

unless condition
output = capture(&block)
concat(output, block.binding)
end
end

Sunday, December 30, 2007

Understanding include and extend in Ruby

I was watching a presentation by Dave Thomas called, "MetaProgramming - Extending Ruby for Fun and Profit", and realized that my understanding of include and extend is mixed up.

My Wrong Understanding
I thought "extend" will add methods from a module into a class as instance methods and "include" will add them as class methods.

Correct Understand:
"extend" adds methods from a module into a class as class methods.
"include" adds methods from a module into a class as instance methods.

It is quite easy to demonstrate this actually.

module SomeModule
def hi
puts "hello"
end
end

class ExtendSample
extend SomeModule
end

ExtendSample.hi

class IncludeSample
include SomeModule
end

IncludeSample.new.hi

Monday, December 17, 2007

AUTO_INCREMENT MySQL

There is a bug in MySQL that reset AUTO_INCREMENT if an index is added and the table is empty. I found a ticket regarding this issue in Ruby on Rails' bug tracker but it won't be fix because it is a MySQL bug.

Anyway, I reset AUTO_INCREMENT to my desire value after adding indexes to the table and that seems to work. Just remember to not add anymore indexes to the table after you set the AUTO_INCREMENT value or else it will be reset again.

Here is how to set the value manually.

execute "ALTER TABLE table1 AUTO_INCREMENT = 100"

Friday, December 14, 2007

added method to help create and drop foreign key

We have a naming convention at my work place for foreign key so I made two methods to help in the creation and dropping of foreign key. I made them because I got tired of typing out the query everytime.

We name our foreign key like this: fk_table_column_reference_table_column. So a foreign key from a "users" table to the "employers" table would look like this. fk_users_employer_id.

This is how you call the method to create a foreign key.


create_foreign_key(:users, :employer_id, :employers, :id)
drop_foreign_key(:users, :employer_id)



def create_foreign_key(table, column, foreign_table, foreign_column)
execute "ALTER TABLE #{table.to_s} ADD CONSTRAINT fk_#{table.to_s}_#{column.to_s} FOREIGN KEY (#{column.to_s}) REFERENCES #{foreign_table}(#{foreign_column})"
end

def drop_foreign_key(table, column)
execute "ALTER TABLE #{table.to_s} DROP FOREIGN KEY fk_#{table.to_s}_#{column.to_s}"
end

Monday, December 10, 2007

NetBeans 6 - Out of Memory Exception

Lately, I have been getting Out of Memory Exception every time NetBeans load up. This is the exception message, "java.lang.OutOfMemoryError: Java heap space". I am using the daily build of the custom ide for Ruby development.

I fixed the problem by setting the max heap size to a 512 MB. This is how I start the ide.

nbrubyide.exe -J-Xmx512m

UPDATE: I just found out that I can set the max heap size in the nbrubyide.conf file. It is in the etc directory under c:\nbrubyide
I modified it to

default_options="-J-Xms24m -J-Xmx256m"

Friday, December 07, 2007

Rails 2.0.1 is out

I am sure this is all over the web but Rails 2.0.1 is out and here is the announcement. I probably won't use it for my current project until after we do a release.

Monday, December 03, 2007

Mongrel installed in wrong location?

I just reinstall my rails stack to use ruby 1.8.6 and mongrel wouldn't start. I kept getting this error instead.

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

Which is strange since Mongrel is one of the install gem when I do gem list. Here are my install gems.

*** LOCAL GEMS ***

actionmailer (1.3.6)
actionpack (1.13.6)
actionwebservice (1.2.6)
activerecord (1.15.6)
activesupport (1.4.4)
capistrano (2.1.0)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
highline (1.4.0)
mongrel (1.1.1)
needle (1.3.0)
net-sftp (1.1.0)
net-ssh (1.1.2)
rails (1.2.6)
rake (0.7.3)

I can see mongrel is installed under mongrel-1.1.1-mswin32 but the system was trying to look for mongrel under mongrel-1.1.1-x86-mswin32-60.

I rename my mongrel directory to mongrel-1.1.1-x86-mswin32-60 and everything works. I wonder if I did something wrong or Mongrel just installed in the wrong directory. I am using gem 0.9.5 and it just figures out the correct version of mongrel and install it by itself so I didn't have the chance to pick which version of mongrel I wanted to install.

Tuesday, July 17, 2007

NetBeans IDE 6.0 M10 is out

Netbeans 6.0 M10 is out. There are many editing and debugging improvement for RHTML files. Here is the new feature sections for Ruby development.

  • Find Usages
  • Rename Refactoring
  • RHTML support
    • Debugging (breakpoints, stepping etc. in RHTML files)
    • Code completion
    • Go to declaration
    • Find Usages
    • Rename
  • Improved code completion - attributes, Rails migrations, models and views now include all the expected methods, etc.
  • Enhanced RDoc rendering; embedded Ruby and RHTML code fragments are now syntax highlighted
  • Debugger enhancements (global vars, watch view, locals view)
  • Encoding support (projects now have an encoding property)
  • Basic RSpec and ZenTest support (More Info), basic RJS support
  • JRuby 1.0 is bundled

Developing ROR using Emacs

I saw a few screencast on using Emacs to do ROR development but I was not able to setup emacs to try it out until I saw this five part series on setting up Emacs for Ruby on Rails development from Software bits and pieces.

http://sodonnell.wordpress.com/the-emacs-newbie-guide-for-rails/

After following guide step by steps I was able to get emacs up and running for developing ROR. Initially emacs started up with an error and it wasn't able to go into ROR mode. I found out I was missing inf-ruby which you can get it here. If you following the tutorial then put this file in your c:/emacs-22.1/includes/ directory. After putting the file there, everything works.

I found another site, credmp, also with instructions on how to setup emacs for ROR development. Ruby On Rails and Emacs It also list out the snippets that the emacs-rails supports.

Monday, July 02, 2007

Build FaceBook Application using Rails

Here are links to two blog articles on how to build FaceBook application using Rails.

From GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS:

fist in your facebook

From Liverail >> Rails with currents:

Tutorial on developing a Facebook platform application with Ruby On Rails

Tuesday, June 19, 2007

Where to put the code

That is the question I ask all the time while developing in Rails. Should I put the code in the helper or in the model or in the controller itself. I guess I need to find some advance Rails reading material. On that note, Roby on Rails has a collection of links to making the model fat and the controller skinny. Put Your Controller on a Diet already!

After reading those blog posts, I am seeing myself putting some serious time in slim up my controllers. They are a little on the heavy side for sure.

Tuesday, May 08, 2007

observe_field and radio_button

I had a group of radio buttons that I wanted to trigger some action when one of the button is selected. I setup an observe_field for each radio button but it didn't work. You can't specify observe_field to monitor a group of radio buttons. It would only monitor the first button. Actually, let me clarify that statement. It would work the first time a user click on the button but then subsequence click would not register as something has changed. Apparently, it keeps the last value and when the radio button is selected again, the last value and the current value is the same. That result in a no change. I ended up using onclick with remote_function to trigger the change event.

This is what I had and it doesn't work.
<%= radio_button_tag 'ship_method', 'pickup', :checked => true -%> Pickup

<%= radio_button_tag 'ship_method', 'deliver' -%> Deliver

<%= observe_field 'ship_method_pickup',
:url => { :controller => 'checkout', :action => 'ship_method_select' },
:on => 'click', :with => 'method' -%>

<%= observe_field 'ship_method_deliver',
:url => { :controller => 'checkout', :action => 'ship_method_select' },
:on => 'click', :with => 'method' -%>
This is what I ended up with
<input type="radio" name='ship_method' id='ship_method_pickup'
checked="checked" value="pickup"
onclick="<%=
remote_function(
:url => {:controller => 'checkout', :action => 'ship_method_select', :method => 'pickup'}
)-%>" />

Monday, May 07, 2007

How to pass a class or id to link_to_remote

This does seem like a really simple thing now that I figured out how to do it.
<%= link_to_remote 'Name',
{:url => {:controller => 'some_controller', :action =>'some_action', :id => some_id}},{ :class => 'some_class' }-%>

If you want to specify a fall back url for href instead of the default # you can put that in the html_options part also.
<%= link_to_remote 'Name',
{:url => {:controller => 'some_controller', :action => 'some_action', :id => some_id}},
{:class => 'some_class', :href => url_for({:controller => 'some_controller', :action => 'some_action', :id => some_id}) }-%>

Saturday, May 05, 2007

NetBeans IDE 6.0 M9 is out

I just saw that NetBeans 6 Milestone 9 was released. Go here to see all the changes for M9. There are many new features added for Javascript. You can edit embedded Javascript and CSS inside HTML/JSP. Of course, there are new features for Ruby editing.

Here is the list of changes for Ruby from the site.

  • Advanced code editing: Code completion, Documentation Popup, Semantic highlighting (such as unused local variable coloring), Parameter Hints, Instant Rename, Goto Declaration, Live Code Templates, Mark Occurrences, Reformatting, Pair Matching, Smart Selection, Surround With

  • Project support: Create and run files, run unit tests, run RSpec specifications, jump between files and their testcases, Ruby Gems support, ability to use any version of either JRuby or native Ruby

  • Ruby Debugger, including Rails debugging - run/step, breakpoints, local variables, call stack, thread switching, balloon evaluation, etc. Support for native fast debugging.

  • Ruby On Rails support: Code Generator wizard, Database Migrations, Rake Targets, Support for generator plugins, Jump between Action and View, RHTML highlighting

Download and try it out for yourself.

Sunday, April 01, 2007

NetBeans IDE 6.0 M8 is out

I just installed NetBeans IDE 6.0 M8 and noticed that you can start and stop WEBrick within NetBeans now. Before this release, you would have to kill the java task from the task manager which was a pain. I actually didn't use WEBrick within the ide because of this problem. Instead, I just run it from the command line using the native ruby interpreter instead of jruby.

Before I was able to use the WEBrick instance started by NetBeans, I need to setup the project to use the jdbc adapter for MySQL. Since I didn't really bother reading much instruction, I encountered quite a few problems.

Here are the steps I used to get everything working.

1. Modify environment.rb and add these lines in right before Rails::Initializer:

if RUBY_PLATFORM =~ /java/
require 'rubygems'
RAILS_CONNECTION_ADAPTERS = %w(jdbc)
end

Rails::Initializer.run do |config|

2. Modify database.yml to use the jdbc adapter. Of course, instead of test_development, you put your own database name there.

development:
adapter: jdbc
driver: com.mysql.jdbc.Driver
username: root
password: password
url: jdbc:mysql://localhost:3306/test_development

3. Download the JDBC driver for MySQL.
Download Connector/J 5.0
Unzip or untar the archive and copy mysql-connector-java-5.0.5-bin.jar to your jruby-0.9.8\lib.

You can find your jruby-0.9.8 directory under
C:\Documents and Settings\<your username>\.netbeans\

I found this step to be quite important because adding the driver to CLASSPATH did not work for me.

NetBeans also exposed more rake tasks than before.

Wednesday, March 21, 2007

How to use migration

Yavor Ivanov over at rubycorner.net started a mini series on Rails migration. So far there is one article and I already learned a few things that I didn't know.

How to use Rails Migrations - Part I

I created a table with :created_at column as :null => false but I didn't define the default value so I was having problem with specifying the datetime in my test fixture.

I solved that problem by putting this in my test fixture:
created_at: <%= DateTime.now.strftime('%y-%m-%d %H:%M:%S') %>
What I really should have done is created the column like this.
t.column :created_at, :datetime, :default => Time.now