Make your own gem - RubyGems Guides. From start to finish, learn how to package your Ruby code in a gem. Introduction ———— Creating and publishing your own gem is simple thanks to the tools baked right into RubyGems. Let’s make a simple “hello world” gem, and feel free to play along at home! The code for the gem we’re going to make here is up on GitHub. Your first gem ————– I started with just one Ruby file for my hola gem, and the gemspec. . % tree . ├── hola.gemspec └── lib └── hola.rb Code for your package is placed within the lib directory. The code inside of lib/hola.rb is pretty bare bones. . % cat lib/hola.rb class Hola def self.hi puts "Hello world!
" The gemspec defines what’s in the gem, who made it, and the version of the gem. . % cat hola.gemspec Gem::Specification.new do |s| s.name = 'hola' s.version = '0.0.0' s.date = '2010-04-28' s.summary = "Hola! " The description member can be much longer than you see in this example. Look familiar? After you have created a gemspec, you can build a gem from it. Let’s try this out. Module: Base64. What's the best way to hash a url in ruby.
Configuration Management. Running a Ruby block as another user - Brizzled. Cool rails apps. Ruby: How do I get the target of a symlink. Ruby Exceptions. Raising An Exception An exception is a special kind of object, an instance of the class Exception or a descendant of that class that represents some kind of exceptional condition; it indicates that something has gone wrong. When this occurs, an exception is raised (or thrown). By default, Ruby programs terminate when an exception occurs. But it is possible to declare exception handlers. An exception handler is a block of code that is executed if an exception occurs during the execution of some other block of code.
Raising an exception means stopping normal execution of the program and transferring the flow-of-control to the exception handling code where you either deal with the problem that's been encountered or exit the program completely. Which of these happens - dealing with it or aborting the program - depends on whether you have provided a rescue clause (rescue is a fundamental part of the Ruby language). Reference: The above figure is from the Programming Ruby book.
The output is:
Ruby Programming/Syntax/Variables and Constants. A variable in Ruby can be distinguished by the characters at the start of its name. There's no restriction to the length of a variable's name (with the exception of the heap size). Local Variables[edit] Example: foobar A variable whose name begins with a lowercase letter (a-z) or underscore (_) is a local variable or method invocation. A local variable is only accessible from within the block of its initialization. i0 = 1 loop { i1 = 2 puts defined? Instance Variables[edit] @foobar A variable whose name begins with '@' is an instance variable of self.
Class Variables[edit] A class variable is shared by all instances of a class and begins with '@@'. @@foobar An important note is that the class variable is shared by all the descendants of the class. This shows us that all our classes were changing the same variable. Global Variables[edit] $foobar A variable whose name begins with '$' has a global scope; meaning it can be accessed from anywhere within the program during runtime. Constants[edit] Usage: Logger. Description¶ ↑ The Logger class provides a simple but sophisticated logging utility that you can use to output messages. The messages have associated levels, such as INFO or ERROR that indicate their importance. You can then give the Logger a level, and only messages at that level of higher will be printed. The levels are: an unhandleable error that results in a program crash a handleable error condition a warning generic (useful) information about system operation low-level information for developers For instance, in a production system, you may have your Logger set to INFO or even WARN When you are developing the system, however, you probably want to know about the program’s internal state, and would set the Logger to DEBUG.
Note: Logger does not escape or sanitize any messages passed to it. Logger.info("User-input: #{input.dump}") logger.info("User-input: %p" % input) You can use formatter= for escaping all data. Example¶ ↑ Features¶ ↑ HOWTOs¶ ↑ How to create a logger¶ ↑ How to log a message¶ ↑ CGI (Ruby 1.8.7) CGI class. See documentation for the file cgi.rb for an overview of the CGI protocol.
Introduction¶ ↑ CGI is a large class, providing several categories of methods, many of which are mixed in from other modules. Some of the documentation is in this class, some in the modules CGI::QueryExtension and CGI::HtmlExtension. For queries, CGI provides methods to get at environmental variables, parameters, cookies, and multipart request data. Read on for more details. Queries¶ ↑ The CGI class dynamically mixes in parameter and cookie-parsing functionality, environmental variable access, and support for parsing multipart requests (including uploaded files) from the CGI::QueryExtension module.
Environmental Variables¶ ↑ The standard CGI environmental variables are available as read-only attributes of a CGI object. For each of these variables, there is a corresponding attribute with the same name, except all lower case and without a preceding HTTP_. Parameters¶ ↑ Cookies¶ ↑ Multipart requests¶ ↑ CAUTION! Eruby. Eruby is a way to embed ruby in HTML. Setup First, obtain a copy of eruby. This is most easily done by using SSH and simply copying /usr/bin/eruby. Name the file eruby.cgi and stick it in the root of the site you'd like to enable ruby on. cp /usr/bin/eruby ~/mysite.com/eruby.cgi Next, create or edit an .htaccess file.
There are two important things to do: make sure .rhtml files get parsed by eruby and make sure apache knows to look for an index.rhtml. DirectoryIndex index.rhtml index.html index.htm AddHandler rubypage .rhtml Action rubypage /eruby.cgi Testing You can use the following simple test to make sure everything is working. <! Encoding issues Note that the compiled in default charset of the eruby program is the iso-8859-1 charset. There are two solutions. Compile eruby with the configure.rb --with-charset=UTF-8 option to change the default charset. It is probably easiest is to override the default character set with the command line option. This has two advantages. See Also External Links. Ruby: Open A File, Write To It, And Close It In One Line. | 398123 views | 1inShare r - Open a file for reading. The file must exist. w - Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. a - Append to a file.
Writing operations append data at the end of the file. The file is created if it does not exist. r+ - Open a file for update both reading and writing. 1.File.open(local_filename, 'w') {|f| f.write(doc) } Ruby and the Web @ Programming Ruby. Ruby is no stranger to the Internet. Not only can you write your own SMTP server, FTP daemon, or Web server in Ruby, but you can also use Ruby for more usual tasks such as CGI programming or as a replacement for PHP.
Writing CGI Scripts You can use Ruby to write CGI scripts quite easily. To have a Ruby script generate HTML output, all you need is #! /usr/bin/env ruby print "HTTP/1.0 200 OK\r\n" print "Content-type: text/html\r\n\r\n" print "<html><body>Hello World! </body></html>\r\n" You could use Ruby's regular expression features to parse incoming query strings, look up environment variables, check tags, substitute text into templates, escape special characters, format up the HTML, and print it all out. Or, you could use class CGI. Using cgi.rb Class CGI provides support for writing CGI scripts. Quoting When dealing with URLs and HTML code, you must be careful to quote certain characters. Require 'cgi' puts CGI.escape( "Nicholas Payton/Trumpet & Flugel Horn" ) produces: Forms Cookies Sessions <!
5 ways to run commands from Ruby | mentalized. Every so often I have the need to execute a command line application from a Ruby application/script. And every single time I fail to remember what the different command-executing methods Ruby provides us with do. This post is primarily a brain dump to aid my failing memory, and it was triggered by an issue with my Redmine Github Hook plugin where STDERR messages were not being logged. The goal of this exercise is basically to figure out how to run a command and capture all its output – both STDOUT and STDERR – so that the output can be used in the calling script. err.rb The test script I’ll be running basically outputs two lines, one on STDOUT, the other on STDERR: #! Kernel#` (backticks) Returns the standard output of running cmd in a subshell.
>> `. STDERR is output, but not captured STDOUT is captured Kernel#exec Replaces the current process by running the given external command. >> exec('. Both STDERR and STDOUT is output. Kernel#system >> system('. IO#popen >> output = IO.popen('. Open3#popen3.