N5ken's technical blog

Just another WordPress.com site

Tag Archives: Ruby

IRB Trick

IRB subsessions let you try things without ending or affecting any of your existing subsessions. The commands to work with subsessions are:

irb start a new subsession
jobs list subsessions
fg # switch to a subsession
kill # kill a subsession

>> my_string = "foo"
=> "foo"
>> irb
>> my_string
NameError: undefined local variable or method `my_string' for main:Object
from (irb#1):1
>> jobs
=> #0->irb on main (#: stop)
#1->irb#1 on main (#: running)
>> fg 0
=> #, @signal_status=:IN_EVAL, @scanner=#>
>> my_string
=> "foo"

Installing mysql2 gem in Mac OS X 10.6.x

It’s very exciting that i can finally install mysql2 on Mac OS X 10.6 successfully!!

solved with

sudo gem install mysql2 -- --srcdir=/usr/local/mysql/include

refer from: https://gist.github.com/972626

it’s really great!!!!! hope this can help you.

Could not find a JavaScript runtime error in rails 3.1

If you are trying out the latest release of rails 3.1, you might encounter a problem that quotes:

Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.

I think this problem will makes the beginner confuse, or it should provides a more explicit message or instruction.

After spending a few minutes searching on the web, I found that you can fix this problem by simply adding gem ‘therubyracer’ into your Gemfile (it’s for Ruby MRI).

gem 'therubyracer

And that’s all folks, enjoy rails 3.1 which integrates jquery, scss, coffeescript, and lots more.. by default :)

[Cheat Sheet] Ruby’s Exception Hierarchy

Well, you could always use Ruby itself, too, that way you’ll always have an up-to-date list:

exceptions = []
tree = {}
ObjectSpace.each_object(Class) do |cls|
  next unless cls.ancestors.include? Exception
  next if exceptions.include? cls
  next if cls.superclass == SystemCallError # avoid dumping Errno's
  exceptions << cls
  cls.ancestors.delete_if {|e| [Object, Kernel].include? e }.reverse.inject(tree) {|memo,cls| memo[cls] ||= {}}
end

indent = 0
tree_printer = Proc.new do |t|
  t.keys.sort { |c1,c2| c1.name  c2.name }.each do |k|
    space = (' ' * indent); space ||= ''
    puts space + k.to_s
    indent += 2; tree_printer.call t[k]; indent -= 2
  end
end
tree_printer.call tree

The hierarchy:

Exception
 NoMemoryError
 ScriptError
   LoadError
   NotImplementedError
   SyntaxError
 SignalException
   Interrupt
 StandardError
   ArgumentError
   IOError
     EOFError
   IndexError
   LocalJumpError
   NameError
     NoMethodError
   RangeError
     FloatDomainError
   RegexpError
   RuntimeError
   SecurityError
   SystemCallError
   SystemStackError
   ThreadError
   TypeError
   ZeroDivisionError
 SystemExit
 fatal

Using Mustache in Rails 3

Mustache is …

So, for binding mustache in your Rails3 project, add the following gems to you Gemfile

gem 'mustache'
gem 'mustache_rails3'

You can enable the mustache template handler by running

rails g mustache:install

Then in RAILS_ROOT/config/initializers/mustache.rb

rails g mustache:install
# Be sure to install mustache gem and include mustache gem in project Gemfile.
# Template Handler
require 'mustache_rails'
# Generator
Rails.application.config.generators.template_engine :mustache
# Need to change dynamically when the theme changed
Mustache::Rails::Config.template_base_path = Rails.root.join('themes', 'n5ken', 'templates')
Mustache::Rails::Config.shared_path        = Rails.root.join('themes', 'n5ken', 'templates', 'shared')

# You can change these defaults in, say, a Rails initializer or
# environment.rb, e.g.:
#
# Mustache::Rails::Config.template_base_path = Rails.root.join('app', 'templates')
module Config
  def self.template_base_path
    @template_base_path ||= ::Rails.root.join('app', 'templates')
  end
  def self.template_base_path=(value)
    @template_base_path = value
  end
  def self.template_extension
    @template_extension ||= 'html.mustache'
  end
  def self.template_extension=(value)
    @template_extension = value
  end
  def self.shared_path
    @shared_path ||= ::Rails.root.join('app', 'templates', 'shared')
  end
  def self.shared_path=(value)
    @shared_path = value
  end
end

If we run scaffold to create a product model, we will get the response messages as follow:

$:/var/projects/template# rails g scaffold Product title:string description:text
      invoke  active_record
      create    db/migrate/20110703090715_create_products.rb
      create    app/models/product.rb
      invoke    test_unit
      create      test/unit/product_test.rb
      create      test/fixtures/products.yml
       route  resources :products
      invoke  scaffold_controller
      create    app/controllers/products_controller.rb
      invoke    mustache
      create      app/views/products
      create      app/views/products/index.rb
      create      app/templates/products/index.html.mustache
      create      app/views/products/edit.rb
      create      app/templates/products/edit.html.mustache
      create      app/views/products/show.rb
      create      app/templates/products/show.html.mustache
      create      app/views/products/new.rb
      create      app/templates/products/new.html.mustache
      create      app/templates/products/_form.html.mustache
      invoke    test_unit
      create      test/functional/products_controller_test.rb
      invoke    helper
      create      app/helpers/products_helper.rb
      invoke      test_unit
      create        test/unit/helpers/products_helper_test.rb
      invoke  stylesheets
      create    public/stylesheets/scaffold.css

From the message, it will generate mainly three folders: controller, view, templates.

Installing REE by RVM in Ubuntu

Installing the REE by RVM in Ubuntu may have the following error, this because you missed some dependencies:

root@ubuntu:~# rvm install ree
Installing Ruby Enterprise Edition from source to: /usr/local/rvm/rubies/ree-1.8.7-2011.03
ree-1.8.7-2011.03 - #fetching (ruby-enterprise-1.8.7-2011.03)
curl: /usr/local/staf/lib/libcrypto.so.0.9.8: no version information available (required by /usr/lib/libcurl.so.4)
curl: /usr/local/staf/lib/libssl.so.0.9.8: no version information available (required by /usr/lib/libcurl.so.4)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 7713k  100 7713k    0     0  57223      0  0:02:18  0:02:18 --:--:-- 50726
ree-1.8.7-2011.03 - #extracting ruby-enterprise-1.8.7-2011.03 to /usr/local/rvm/src/ree-1.8.7-2011.03
ree-1.8.7-2011.03 - #installing 
ERROR: Error running './installer -a /usr/local/rvm/rubies/ree-1.8.7-2011.03  --dont-install-useful-gems ', please read /usr/local/rvm/log/ree-1.8.7-2011.03/install.log
ERROR: There has been an error while trying to run the ree installer. Halting the installation.

So, now you just need:

sudo apt-get install build-essential zlib1g-dev libssl-dev libreadline6-dev

Useful commands in RVM

RVM is a good tool for managing Ruby and Gems, so the following codes shows you how to use:

Ruby Management

Use a particular Ruby

$ rvm use 1.8.6

Equivalently (because of RVM’s defaults):

$ rvm 1.8.6

List Ruby interpreters available for installation

$ rvm list known
  # MRI Rubies
  [ruby-]1.8.6[-p399]
  [ruby-]1.8.6-head
  [ruby-]1.8.7[-p330]
  [ruby-]1.8.7-head
  ...bla bla bla

List Ruby interpreters you’ve already installed

$ rvm list

   ruby-1.8.6-p383:  ruby 1.8.6 (2009-08-04 patchlevel 383) [i686-darwin10.0.0]
   ruby-1.9.1-head:  ruby 1.9.2dev (2009-10-30 trunk 25559) [x86_64-darwin10.0.0]
   ...bla bla bla

Ruby information for the current shell

$ rvm info

rvm 0.0.49 (2009.09.24) [http://rvm.beginrescueend.com/]

ruby:
interpreter:  "ruby"
version:      "1.8.6"
...bla bla bla

Install a specific Ruby version, e.g.

$  rvm install jruby

or

$  rvm install 1.9.2

Switch to gems directory for current ruby

$ rvm gemdir

/Users/wayne/.gem/ruby/1.9.1

Switch to the system gems directory

$ rvm gemdir system

/Library/Ruby/Gems/1.8

Use the user set default ruby

$  rvm default

Use the system ruby (as if no rvm)

$  rvm system

Reset to pre-RVM state.

$  rvm reset

Uninstall RVM installed 1.8.7 version

$  rvm uninstall 1.8.7

Named Gem Sets
Examples of creating and changing gem sets

$ rvm 1.9.2-head
$ gem install rails -v 2.3.3

$ rvm gemset create rails222 rails126
Gemset 'rails222' created.
Gemset 'rails126' created.

$ rvm 1.9.2-head@rails222
$ gem install rails -v 2.2.2

$ rvm 1.9.2-head@rails126
$ gem install rails -v 1.2.6

$ rvm 1.8.7
$ gem install rails -v 1.2.3

If you are deploying to a server or you do not want to wait around for rdoc and ri to install for each gem then you can disable these for gem installs and updates. Place these two lines in your ~/.gemrc or /etc/gemrc:

install: --no-rdoc --no-ri
update: --no-rdoc --no-ri

First play of RVM (Ruby Version Manager)

Due to the development environment is becoming much more complex than ever, the gems now may have conflict between some projects, so RVM is what exactly you need!

So RVM is not Ruby Virtual Machine, it’s Ruby Version Manager which is used to separate your various Ruby environment, by Using the RVM, you are able to install, uninstall difference Ruby, e.g. Ruby 1.8.x, 1.9.x, REE, IronRuby, and managing gems..

RVM is cool, right? so now, i think you can’t wait to have a try :)

Installing RVM is quite easy, firstly, you need to confirm the following dependencies, my OS is Ubuntu 10.10:

cURL (apt-get install curl)

If you are ready, you just need to execute this command to finish the installation:

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

and add the line below to your bash profile, for example in Ubuntu is “/etc/profile”

[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # This loads RVM into a shell session.

Back to the command line, run “rvm -v”, and you should see the version information:

$ source /etc/profile
$ rvm -v
rvm 1.6.20 by Wayne E. Seguin (wayneeseguin@gmail.com) [https://rvm.beginrescueend.com/]

So, by now, you have finished the installation of RVM, congratulation!!!

Using Ruby STAF interface on Ubuntu

As we know, STAF is a fantastic test automation framework which supports Java, Python, C++ perfectly except Ruby. but there still a solution for this, in the following post, there is an interface for the original Ruby:

http://sourceforge.net/tracker/index.php?func=detail&aid=643842&group_id=33142&atid=407383

But while I’m trying to compile this library according to this post on Ubuntu, i got:

root@ubuntu:~/Downloads/rubystaf# ruby extconf.rb
checking for STAFRegister() in -lSTAF... no
creating Makefile

It because of missing the required libraries, so include the path to STAF installation path:

root@ubuntu:~/Downloads/rubystaf# ruby extconf.rb --with-staf-dir=/usr/local/staf/ --with-staf-lib=/usr/local/staf/lib
checking for STAFRegister() in -lSTAF... yes
creating Makefile

Then we can create the “Makefile” successfully

Next, run “make” to make the library, but some errors occur here

root@ubuntu:~/Downloads/rubystaf# make
gcc -I. -I/usr/local/ruby/include/ruby-1.9.1/i686-linux -I/usr/local/ruby/include/ruby-1.9.1/ruby/backward -I/usr/local/ruby/include/ruby-1.9.1 -I. -I/usr/local/staf//include  -D_FILE_OFFSET_BITS=64  -fPIC -O3 -ggdb -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long  -o STAFHandle.o -c STAFHandle.c
STAFHandle.c: In function ‘sh_new’:
STAFHandle.c:74: error: ‘rb_get_argv’ declared as function returning an array
STAFHandle.c:74: error: conflicting types for ‘rb_get_argv’
/usr/local/ruby/include/ruby-1.9.1/ruby/intern.h:571: note: previous declaration of ‘rb_get_argv’ was here
STAFHandle.c:90: warning: initialization makes pointer from integer without a cast
STAFHandle.c:101: error: subscripted value is neither array nor pointer
STAFHandle.c:102: error: subscripted value is neither array nor pointer
STAFHandle.c: In function ‘sh_submit’:
STAFHandle.c:122: warning: assignment makes pointer from integer without a cast
STAFHandle.c:123: warning: assignment makes pointer from integer without a cast
STAFHandle.c:124: warning: assignment makes pointer from integer without a cast
make: *** [STAFHandle.o] Error 1

As we can see, there is a conflicting types in line 74, 101 and 102, because in ruby 1.9.x “rb_argv” was changed to “rb_get_argv”, so just rename the variant name from “rb_argv” to “rb_get_argv” and make again:

http://www.ruby-forum.com/topic/153426

root@ubuntu:~/Downloads/rubystaf# make
gcc -I. -I/usr/local/ruby/include/ruby-1.9.1/i686-linux -I/usr/local/ruby/include/ruby-1.9.1/ruby/backward -I/usr/local/ruby/include/ruby-1.9.1 -I. -I/usr/local/staf//include  -D_FILE_OFFSET_BITS=64  -fPIC -O3 -ggdb -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long  -o STAFHandle.o -c STAFHandle.c
gcc -shared -o STAFHandle.so STAFHandle.o -L. -L/usr/local/ruby/lib -Wl,-R/usr/local/ruby/lib -L/usr/local/staf/lib -Wl,-R/usr/local/staf/lib -L/usr/local/staf//lib -Wl,-R/usr/local/staf//lib -L.  -rdynamic -Wl,-export-dynamic   -lSTAF  -lpthread -lrt -ldl -lcrypt -lm   -lc

After this step, we should see “STAFHandle.so” in the build path, now for using this library, just simply copy “STAFException.rb”, “STAFResult.rb” and “STAFHandle.so” under the directory named “staf”

For the testing, we can create a new ruby file and run the code below:

$LOAD_PATH << '.'

require 'STAFCommand.rb'

staf_result = STAF::STAFCommand.new 'local', 'ping', 'ping'

puts "STAF rc: #{staf_result.rc}"
puts "STAF result: #{staf_result.result}"
puts "Error message: #{staf_result.errorMsg}"

If no error come up, that means you have build the STAFHandle for Ruby properly~ :)

NOTE:

If you are using Ruby 1.9.x, you will receive:

ruby: symbol lookup error: /root/Downloads/rubystaf/staf/STAFHandle.so: undefined symbol: STR2CSTR

It because STR2CSTR was deprecated in ruby 1.9.x, so we need to use StringValuePtr instead, so you need to open the  ”STAFHandle.c” to replace all STR2CSTR and compile again

refer to: http://isitruby19.com/sqlite3-ruby

Follow

Get every new post delivered to your Inbox.