You are on page 1of 9

puts e e k s t o r G e e k s "

val= "7' 1.3:PackageManagement with RUBYGEMS


#using boolean expressions
if val = 7 a.13 Define RUBYGEMSs?
break Ans.: RubyGems is a package managerfor the Ruby
end programming language that provides a standard
format for distributing Ruby programs and
# ending of ruby do.while loop
libraries (in a self-contained format called a "gem"),
end
a tool designed to easily manage the installation of
Output gems, and a server for distributing them. It was
GeeksforGeeks created by Chad Fowler, Jim Weirich, David Alan
Black, Paul Brannan and Richard Kilmer during
RubyConf 2004.

The interface for


RubyGems is a command-line tool Q.15 Define structure of RubyGems ?
called gem which can install and manage libraries Ans. Every gem contains a name, version and
the gems). RubyGems integrates with platform. Gems work only on ruby designed for a
Ruby run-
time loader to help find and load installed gems particular platform based on CPU architecture and
from standardized operating-system type and version. Each gem consists
library folders. Though it is
possible to use a private RubyGems repository, of:
the public 1. Code
repository is most commonly used for
gem management. 2. Documentation
The
public repository helps users find gems, 3. Gem specification (Gemspec)
resolve dependencies and install them.
RubyGems The code organization follows the following structure
is bundled with the standard
Ruby package as of for a gem called gem_name:
Ruby 1.9
gem_name/
Q.14 Explain the history of RubyGems?
Ans.:
gem_name
Development on RubyGems started in November
ID/
2003 and released to the
was
public on March 14,
2004, or Pi Day 2004.[4] In 2010, the default -gem_name.rb
public
repository for gems moved from tesu

http://gems.rubyforge.org to http://rubygems.org test gem_name.rb


which is still in use. Also, RubyGems development README
was moved to GitHub in 2010. Though RubyGems
Rakefile
has existed since Ruby 18, it was not a part of the
standard Ruby distribution until Ruby 1.9. gem_name.gemspec
The lib directory contains the code for the gem.
Previously, compatibility with RubyGems and Ruby
varied. Many versions of RubyGems are almost The test (or spec)
directory is used for testing.
fully incompatible with many versions of Ruby and Rakefile is used by Rake to automate tests and to
some versions had key features unusable. For generate code.
example, Ruby 1.9 came with RubyGems 1.3.7 in its README includes the documentation, RDOC, for
standard distribution, but RubyGems 1.4.x was not most gems.
compatible with Ruby 1.9. This meant that updating Gem specification (gemspec) contains information
RubyGems on Ruby 19 was not possible until about the author of the gem, the time of creation
RubyGems 1.5.0 was released in 2011, two years and the purpose the gem serves.
after the first stable release of Ruby 1.9. These Q.16 Explain the working principle with gems ?
compatibility issues led to a rapid development of Ans.: Gems are packages similar to Ebuilds. They
RubyGems, switching to a 46 week release contain package information along with files to install.
schedule. This is reflected in there being 38 releases
Gems are usually built from "gemspec" files, which
from 2004 to 2010 and 117 releases from 2011 to
are YAML files containing information on
gems.
2016. 45 versions were released in 2013, which is the
highest number of releases in a year for RubyGems.
However, Ruby code may also build gems directl
Such a practice is usually used with Rake
gem commandjedit]
Scripting similar way as we used to do in Web
scripts.
Typically a Web service does not have a user interface
that can be used for scripting. So in that case, we need 1.8: RubyTk
todepend the
developmernt team to get the SOAP
on
Q.36 Describe the introduction of RubyTk?
data that the web service takes as input and their
Ans.: The standard graphical user interface (GUI) for
corresponding success and failure codes.
Ruby is Tk. Tk started out as the GUI for the Tcl
We have 3 ways that LR be used for
can
scripting: scripting language developed by John Ousterhout.
1. Using soap_request
.Tk has the unique distinction of being the only
2. Using a WSDL wizard.
cross-platform GUL. Tk runs orn Windows, Mac, and
3. Using web_custom_request. Linux and provides a native look-and-feel on each
1. Using soap_request operating system.
1. .The basic component of a Tk-based application is
Open VuGen and create a Web Services script. called a widget. A component is also sometimes
2. Create call in the Action.
a
soap_request called a window, since, in Tk, "window" and
soap_request('StepName=",
"URL=", "widget" are often used interchangeably.

"SOAPEnvelope="
"Snapshot= ",
Tk applications follow a widget hierarchy where
any number of widgets may be placed within
"ResponseParam= "
another widget, and those widgets
within another
LAST);
widget, ad infinitum. The main widget in a Tk
StepName Text describing the Web Services step
program is referred to as the root widget and can be
(Any free text).
created by making a new instance of the TkRoot
URL -URL of the Web service
class.
SOAP Envelope This field has the XML string that is
accepted by the web service. The AD team should

Most Tk-based applications follow the same cycle:


If you would run this script, it would produce the

following result -
Create the widgets, place them in the interface, and
finally, bind the events associated with each widget
to a method. 1.10: Ruby/Tk WidgetClasses
There are three geometry managers; place,
Q.39 Explain Ruby/Tk widget classes ?
grid and pack that are responsible for controlling the
Ans.: There is a list of various Ruby/Tk dasses, which
size and location of each of the widgets in the
can be used to create a desired GUl using Ruby/Tk.
interface.
TkFrame creates and manipulates frame widgets.
Q.37 Define the Installation of RubyTk?
TkButton creates and manipulates button widgets
Ans.: The Ruby Tk bindings are distributed with Ruby
but Tk is a separate installation. Windows users can .TkLabel creates and manipulates label widgets.
download a single cick Tk installation from Active .TkEntry creates and manipulates entry widgets.
check
State's ActiveTcl.
TkCheckButton creates and manipulates
Mac and Linux users may not need to install it because button widgets
there is a great chance that its already installed along and manipulates radio
TkRadioButton creates
with OS but if not, you can download prebuilt button widgets.
packages or get the source from the Tel Developer.TkListbox creates and manipulates list box widgets
Xchange. and list box
TkComboBox creates manipulates
1.4: Ruby and Web

Q.17 Define RUBY and WEB ?


all. Even so, web
Ans.: Ruby general-purpose language; it can't properly be called a web language at
is a

most common uses of Ruby.


applications and web tools in general are among the
server in Ruby, but you can also
Not only can you write your own SMTP server, FTP daemon, or Web
CGl programming or asa replacement for PHP.
use Ruby for more usual tasks such as

a.18 Explain writing CGl scripts?


Ans.: Writing CGIScripts
The most basic Ruby CGI script looks like this-
#/ust/bin/ruby
puts "HTTP/1.0 200 OK"
puts "Content-type: text/html\n\n"

puts"<html> <body> This is a test </body> </html>"

I you call this script test.cgi and uploaded it to a Unix-based Web hosting provider with the right
permissions, you could use it as a CGI script.
FOr if you have the Web site https://www.example.com/hosted with a Linux Web hosting
example,
provider and you upload test.cgi to the main directory and give it execute permissi a5, then
VISiting https://www.example.com/test.cgi.should return an HTML page saying This is a test.
Here when test.cgi is requested from a Web browser, the Web server looks for test.cgi on the Web site, and
then executes it using the Ruby interpreter. The Ruby script returns a basic HTTP header and then
retums a basic HTML document.

Using cgi.rb
Ruby comes with a speial library called cgi that enables more sophisticated interactions than those with
the preceding CGI script.
Let's create a basic CGI script that uses cgi-
#l/usr/bin/ruby

require cgi'
cgi = CG" new

puts cgi.header
puts<html><body> This is a test </body> </html>"
Here, you created a CGI object and used it to print the header line for you.
class return while Q.6 Explain Rails ?

det Ans.: Rails is a software library that extends the


self
FILE David Heine Meier
Ruby programming language.
defined? module Super LINE Hansson is its creator. He gave it the name "Ruby
Q.5 Describe syntax of Ruby with an example ? on Rails," though it is often just called "Rails."
Ans.: Ruby BEGIN Statement I t is software code that is added to the Ruby
programming language. Technically, it is a package
Syntax
library (speifically, a Ruby Gem), that is installed
BEGIN
using the operating system command-line
code
interface.
Declares code to be called betore the program is run. .Rails is a framework for building websites. As such,
Rails establishes conventions for easier collaboration
Example and mainternance. These conventions are codified as
#l/ust/bin/ruby the Rails API (the Application Programming
Interface, or directives that control the code). The
puts "This is main Ruby Program"
Rails APl is documented online and described in
books, articles, and blog posts. Learning Rails
BEGIN means learning how to use the Rails conventions
puts "Initializing Ruby Program*
and its AP
Rails combines the Ruby programming language
This will produce thefollowing result-
with HTML, CSS, and JavaScript to create a web
Initializing Ruby Program
application that runs on web server. Because it
This is main Ruby Program
runs on a web server, Rails is considered a
server
Ruby END Statement side, or "back end" web application development
platform (the web browser is the "front end"). Later,
Syntax
END{ this article will describe web applications in greater
code depth and show why a web development
framework is needed to build complex websites
Declares code to be called at the end of the program.
Rails, in a larger sense, is more than a software
and APL. Rails is the central project of a
Example library an

#l/ust/bin/ruby vast community that produces software libraries


that simplify the task of building complex websites.
puts "This is main Ruby Program"
Members of the Rails community share many core
values, often use the same tools, and support each
END {
puts Teminating Ruby Programn other with an informal network that is built on
volunteerism. Overlapping the informal community
BEGIN
is an economic network that includes jobs,
puts Initializing Ruby Program"

recruiters, consulting firms, conferences, businesses The advantage of establishing conventions might
that build websites with Rails, and investors that seem obvious, but when Rails released in 2004,
was

fund startups. Rails is popular among web startups, web development was dominated by PHP, which
signiticantly because the pool of opern source lent itself to idiosyncratic code produced by solo
software libraries (RubyGems, or "gems") makes it webmasters, and Java frameworks such as Struts,
possible to build complex sites quickly which were often seen as burdened by an excess of
Read on for a more detailed look at Rails. First, we'll structure.Other frameworks, such as Apple's
look at why Rails uses the Ruby programming WebObjects, Adobe's ColdFusion, and Microsoft's
language. We'll consider why Rails is popular, NET Framework, were in wide use but the
review some basic concepts, then look at Rails from frameworks were products controlled by the
six different perspectives to understand it better. companies and built by small teams, which tended
2.1:Extending Ruby VALUE CTest;
* void Init _my_test(1
Q.1 Define extending ruby. CTest= rb_define_class("MyTest, rb_cObject):
Ans.: It is easy to extend
Ruby with new
features by rb_define_method(cTest, "initialize', t_init, 0):
writing code in
Ruby. Once you start Tb_define_method(cTest, "add"t_add, 1):
low-level code written in C, adding in id push = rb_intenml'push");
however, the
possibilities are endless.Extending Ruby with C is
pretty easy. For instance, suppose we are
a custom
building 2.2.1:Bullding Our Extension
Internet-ready jukebox for the Sunset
Diner and Grill. Q.2 What is building our extenslon ?
.The extension we write will have Ans.: We'll have a lot more to
the same say about building
functionality as the following extensions later. For now,
though, all we have to do is
Ruby class. follow these steps.
class MyTest def initialize@arr Array.new end = Create a file called extconf.rb in the
def add(obj) @arr.push{obj) end as our my_test.c C source file
same
directory
end
file. The file extconf.rb should contain the
That is, we'll be
writing an extension in C that is following two lines.
plug-compatible with that Ruby class.
require 'mkmf
The
equivalent code in C should look somewhat
Create makefile("my_test")
familiar.
Run extconf.rb. This will
#inchude 'ruby h" generate a Makefile.
static int id
push; % ruby extconf.rb
static VALUE _init(vVALUE self)
Creating Makefile
Use make to build the extension. This is what
VALUE ai
arr = rb_ary_new(); happens on an OS X system.
rb_iv_set(self, "@arr, arr); % make
return self;
gcc-fno-common-8-02-pipe -fno-common-I.
static VALUE _add(VALUE self, VALUE obj) .-lusr/lib/ruby/1.9/powerpc-darwin7.4.0
VALUE arr
.-I/usr/lib/ruby/1.9/powerpc-darwin74.0 «
arr = rb_iv_get(self, "@arr);:
my_test.c
Tb_funcall(ar, id _push, 1, obj);
cc
dynamic -bundle -undefined suppress
return arr; -flat_namespace

lusT/ib -o my_test bundle my_test o-ldl lobjc A class is u*d to speity the torm ot an oOet ant
The result of all this the extension, all
n
ncely t combines data rupreentatuon and methede tr
bundled up in a shared object manipulating that data nto one neat packag The
(a so
dll, or fon 0S X]a bundle) data and ethods within
class ar talini
members of the class
2.1.2 Rules for Running Our Extension
2.2.1: Working of Immediate Objects
Q.3 What b rules for running our extenslon ?
Ans. We can use our extension from a.5 Define Working of Immediate Objecte
Ruby simply
by require-ing it dynamically at runtime (on most Ans. : As we said above, immediate vaiues
a o
platforms) We can wrap this up in a test to verity pointers Fixnum, Symbol, true. tale, and nil are
that
things are working as we expect. stored directly in VALUE
require my_test Fixnum values are stored as 31-bit numbersl that
require test/unie' are formed by shift1ng the onginal number lett

class TestTest< Test:Unit: TestCase bit and then setting the 1SB. or least significant bt
def test_test (bit 0). to l When VALUE is used as a pointer te
specific Ruby structure, it is guaranterd always to
t-MyTest.new have LSB of
an zero. the other immediate values
assert_equal(©bject, MyTest.superclass) also have LSB» of zero Thus,
assert equal(My
Test, t.class) a
s1mple bit test can
tell you whether you have a Fixnum This test is
tadd(1) Wrapped in a macro, FIXNUM_P
tadd(2) Similar tests let you check tor ther
assert_equal([1.2], tinstance_eval("@arr")) values.
immediat
end
FIXNUM_P(value) nonzero it value is
a
end
Fixnum
produces: .SYMBOL_P(value)
Finished in 0.000479 seconds.
nonzero if value 1
Symbol
1 tests, 3 assertions, 0 failures, 0 errors NIL P(value) - nonzero if value is nil
Once we're happy that extension works, RTEST(value)- nonzero if
our we value neithet
can then install it globally by nor false
is
ni
running make install.
T h e other immediate aluo
Cusr/lib -o
my_test.bundle my_testo -ldl-lobjc A class is used to specity the torm of an obut and
The result of all this the extension, all it combines data repre*ntation and methoxds for
is
nicely
bundled up in a shared object (a .so, manipulating that data into one neat package The
dll, or lon OS XJ data and methods within class calied
a bundle) a
ar
members of the class

2.1.2 Rules for Running Our Exteslon


2.2.1:Working of Immediate Objects
a.3 What le rules for running our extenslon?
Ans.: WNe a.5 Define Working of Immediate Object
can use
our extension from Ruby simply
said above, immediate values
by require-ing it dynamically at runtime (on most Ans.: As we
arv
platforms). We can wrap this up in a test to verity pointers Fixnum, Symbol, true. false, and nil ars
that things are working as we expect. stored directly in VALUE.
require my_test Fixnum values are stored as 31-bit numbersl that
require 'test/unit' are formed by shifti1ng the original number lett
bit and then setting the LSB, or least significant bt
class TestTest< Test:Unit::TestCase
(bit 0). to 1. When VALUE is used as a pointer t a
def test_test
specific Ruby structure, it is guaranteed alwaysto
t-MyTest.new have LSB of the other immediate values
an
zero,
assert_equal(Object, MyTest.superclass) also have LSBs of Thus,
zero a
simple bit test can
assert_equal(MyTest, t.class) tell you whether you have a
Fixnum. This test is
t.add(1) Wrapped in a macro, FIXNUM_P.
t.add(2) Similar tests let you check for other immediate
assert_equal([1,2], tinstance_eval("@arr")) values.
end
FIXNUM_P(value)- nonzero if value is a
end Fixnum

produces: SYMBOL_P(value)- nonzero if value is a


Finished in 0.000479 seconds. Symbol
1 tests, 3 assertions, 0 failures, 0 errors NIL P(value) nonzero if value is nil
Once we're happy that our extension works, we RTEST(value) nonzero if value is neither nil
can then install it nor false
globally by running make instal.
The other immediate values (true, false, and nai
2.2: Ruby Objects in C are
represented in C as the constants Qtrue Qfalse
and Qnil, respectively You can test VALUE
Q4 What are ruby objects in C? vanables against these constants
directly or use the
Ans.:Ruby is a pure object-oriented language and conversion macros (which
perform the prope
everything appears to Ruby as an object. Every
casting)
value in Ruby is an object, even the most primitive
things: strings, numbers and even true and false.
Even a class itself is an object that is an instance of
the Class class.

void (free)), c-type * )


2.5:
2.4:Embedding Ruby to Other Languages Embedding a Ruby Interpreter
a12 Define embedding a ruby interpreter.
2.4.1: The Basic Procedure for Creating an Ans. : In add1tion to extending Ruby by adding C
Extension code. you can also fum the
problem around and
embed Ruby itself within your
a10 Llst the basic
procedure for creating an extenslon. application.
You have two
Ans. ways to do this The first is to letthe
1. Create the C source code interpreter take control by
calling ruby_run. This is
file{s) in a
given directory the easiest
2 Optionally create approach. it has one but
significant
any supporting Ruby files in a lib drawback-the interpreter never returns
subdirectory from à

3. Create extconf.rb
ruby nun
call Here's an
example
inchude 'ruby h
K u n extcont.rb to
create a Makefile for the C files
this directory
in an(vola)
O u r own applicatiorn stuff. "/
5. Run make.
ruby_init(
6. Run make
install. ruby_init_loadpath().
ruby_scriptl'embedded').
2.42:To Create tD_Joad_ hle('start rb')
A File
ruby_nun().
a.11 Define to create a file. exit{0): }
Ans.: C
data type wrapplng 1o initialize the
Ruby interpreter, you need
VALUE to call
mark). Data_WrapStructlVALUE
vod ("freeXO. "ptr)void
class. void
ruby_inat)
to take
But on some
plattorms, you may need
special steps before that.
Wraps the given C datary pe ptr, registers the "if defined(NT) Ntinitialize(&argc,
two &argv)
garbage collection routines (ee below), and retums endif
a #if
TErMA detined(MACOS&a defned MWERKS
argc ccommand(&argv).
endif Let's write a C program that calls an instance of ths
aenned
HNCA
argc= ccommand(&argv).
Lets rile C
"endif a
program that calls an instance of this
ee main.c class multipe times. To create the instance.
in the Ruby distribution tor any other
welget
special detines the class object (by looking tor
or
setup nevded for yonur
platform
a
top-level comstant
Tou whose n.anme is the
ne the Ruby name of our class) Wel then a<k

actessiDIe
inchude and ibrary hles
Ruby to create an instance
to
cumpile this embedded oxde On my o tha
box (Mac 0S X) I have the
Ruby 18
mterpreter
lass-rb_class_new_instanoe
lass.new. he two
s
actualy a call to

installed in a nutial
parameters are the
private directory, so my Makefile
looks like this argument count and dummy pointer to the
arguments themselves.)
WHERE-/Usersidave/nuby1 Nib/ruby/1 8/powerp O n c e we have that
object, we can invoke t s sum
darwin/ CFLACS-S(WHERE) method ustng rb_funcall
LDFLAGSLS(WHERE) -Iruby -dl -lobjc embet #include ruby.h
embed
oS(CC)-o embd embedo S(LDFLAGS) static int id_sum
The second of int Vahues||l =(5. 10, 15, -1. 20. 0)
way embedding Ruby alkws
Ruby
code and your C code static VALUE Wrap_sum(VALUE args)
to
engage in more of a

dialogue. the C code calls some Ruby code, and


the VALUE "values
Ruby code
responds o u do this by
initializing the
=
(VALUE "jargs
interpreter as normal Then,
ALUE summer values0.
rather than
entering ALOE max values|1].
the return tb_huncall( summer. id_sum, 1. max).
merpreter s mairn loop. you instead invoke
specific methods in your Ruby code. When these
methods return, your C code
static VALUE protected sum(VALUE summer
gets control back VALOE max)
There's a wrinkle, though.
If the int error. VALUE
Ruby code raises an
excepthon anmu
s args|21.
caught, your program C terminate. To will
VALUE result: args|0) =
summer.

overcome this. you need to do what the


args|1max
interpreter result b_protect{wTap_sum. (VALUE }args
does and protect all calls that could raise an error).
etum error 7 Onil resut.
exeption. Ihis can get messy.
he rb-protect method call Wraps the call to
int main(vo1d)
another C function That second function should
invoke our Ruby method. However, the method vaiue

int "next Values,


wrapped by rb_protect is defined to take just a
ruDy init().
single parameter
l o pass more involves some ugy C casting Lets
ruby_init _loadpath()
ruby_script['embedded )
0 a t an example. ieres a simple Ruby class that ID_requirel sum ib). 7 get an instance of Summer
nplements a method to return the sum of the vALDE Summer _classnew_instance(0 0

numbers trom one to max. class Summer TD_const


" e
get_coDect,Sum)
b_ntem('Summer))
1ef sum{max)
whle (value next +*)
Invaid n
if
if max
um {max)"
max c<0Of(max"max+ maxjre VALUE result =
protected sumísummer
INT2NUM(vah
nd f (NIL _Ptesuit)

PprneiSum to >d doesnt computel'n' valuei


else printf("Sum to %d 1s %d\n", value, Q
NUM2INT(result).

rubyfinalize()
exit(0)
API Embedded Ruby APl void ruby_init() Sets C

the interpreter. This function


up and initializes
should be called before any other Ruby-related
functions.
void ruby int_loadpath()
necessary if
Initializes the $: (load path) variable;
libraiy modules.
your code loads any
"argv )
*
char
void ruby_options( int argc.
the command-line
Gives the Ruby interpreter
optiuns.
char "name
void ruby_script( 'and $0) to name.
Sets the n a m e of the Ruby script
void rb_load_file( char 'file)
Loads the given file into the interpreter.
void ruby_nun( ) Runs the interprete.
Shuts dovwn the interpreter
void ruby finalize()
For another example of embedding Ruby a

also eruby.
within another program, see
interpreter
we've
.Bridging Ruby Languages So far,
to Other
routines
discussed extending Ruby by adding
written in C.
can just about
write extensions in
Howeve, you
can bridge the
two
as long as you
any language,
Almost anything is possible,
languages with C.
and C+,
awkward marriages of Ruby
including
But you may be able to
Ruby and Java, and so on.

without resorting toC


accomplish the same thing
could bridge to other
code. For example, you
middleware such as SOAP or

languages using
COM.

You might also like