Ruby

The ability to treat a string as a file can often be quite handy. Generally this most useful when classes/methods expect a file object as an input type. With Ruby, you can use the StringIO library to use a string when a file is expected, thus allowing operations such as read, write, rewind, etc.

In the lines below, the code after the #=> shows the results when executing the script. Follow the code to see several examples of a string using operations that are typically reserved for files.

require 'stringio'
str = StringIO.new %{This is a test of a string as a file. \r\n
                     And this could be another line in the file}

# Get a line
str.gets # => "This is a test of a string as a file. \r\n"

# Get the next 18 charaters
str.read(18) # => " And this could be"

# Seek to new position and read 7 more characters
str.pos = 59  # => 59
str.read(7) # => "another"

# Rewind the file and overwrite some of the existing text
str.rewind
str.write("Here's how to use")

# Rewind again and output the new contents
str.rewind
str.read # => "Here's how to use a string as a file.
     \r\n And this could be another line in the file"
str.eof? # => true

Any easy way to work with a string in a method that is expecting a file is to create a new StringIO object and pass the result to the method requiring a file type. For example:

  some_method(StringIO.new("Your string here"))

Although an array within Ruby supports all the operations you need for working with a stack (push, pop, etc), the problem is, Ruby does not offer a “formal” stack object and therefore the flexibility of the Ruby array can present problems. For instance, even if you intend to treat an array as a stack, nothing will stop you (or another developer using your code) from inserting or deleting anywhere within the stack.

We can work around this by creating a simple Stack class as follows:

class Stack

  def initialize
   @the_stack = []
  end

  def push(item)
    @the_stack.push item
  end

  def pop
    @the_stack.pop
  end

  def count
    @the_stack.length
  end
end

Here is how you might use the stack:

  stack = Stack.new
  stack.push('abc')
  stack.push(100)
  stack.count
  stack.pop()

If need be, you could also add a few convenience methods such as clearing the stack or looking at the last element (without popping it off the stack):

  def clear
    @the_stack.clear
  end

  def look
    @the_stack.last
  end

Give this a try if you need to work with an array as a stack and want to play within the rules of how a stack is implemented as a traditional data structure.

When working in TextMate, if you have a one or more lines of Ruby code that you would like to have the interpreter run, without the need for passing the entire file to the interpreter, this tip may be just what the doctor ordered.

For example, when debugging, often times it would be really handy to run a simple script at a specified location in your code to look at a value, call a method on an Object… The key point here is that you can have as little as one line of Ruby processed by the interpreter and the return value will be inserted inline.

This easiest way to get the gist of this is to watch the screencast below:

If you want to insert the results of one or more lines of script, directly into your code, using # => markers is the way to go.




The music in the video is J.J. Cale and the song: Call Me the Breeze.

A longer clip of J.J. Cale jamming:

What do NetBeans, Ruby and AppleScript have in common? There’s a circular definition of sorts to explain…to start, all are tools available to developers working on Mac. Next, NetBeans has full support for creating, debugging and packaging Ruby code. And finally, Ruby (with the right tools in place) can be used within NetBeans to control scriptable applications on a Mac, something which is typically accomplished using AppleScript.

In this post I’ll describe more about how all these tools come together to provide an interesting approach for using Ruby as an alternative to AppleScript, and working with NetBeans as the development environment for writing and building those same applications.

The screencast that follows will walk you through all the steps to download the tools you’ll need, build from source a scripting bridge (rb-appscript) for Ruby to AppleScript, and finally, create several short examples to demonstrate how you can use Ruby, from within NetBeans to control scriptable applications.

For more information, follow these links:

If you are interested to learn more about using Ruby as an alternative to AppleScript, I’ve written as series of posts you can find here: Part 1, Part 2, Part 3, Part 4, Part 5, Part 6

If you write an interesting application in NetBeans, using Ruby and rb-appscript, drop me a note, as I’d like to post several good examples showing the interaction of all these tools.

As an aside, NetBeans is sponsoring a blogging contest for the 6.1 Beta. If you are interested in learning more, visit the NetBeans Blogging Contest. And who knows, you could walk away with one of ten $500 American Express gift certificates!

In this post I’ll show how to use the interactive help system within rb-appscript to explore the scripting interface for an application. To begin, you’ll need to verify that you have installed ASDictionary version 0.9.0 or later. You can download ASDictionary from here.

I would recommend you verify the path to the Ruby interpreter within the ASDictionary preference settings. To determine the location of the Ruby interpreter on your system, enter which ruby in a terminal:

Copy the path (where Ruby is located on your system) into the Preferences dialog for ASDictionary as shown below. That should do it for configuration.

The best way to understand how the interactive help works is to go through an example. So, let’s say that you are interested to get the name of every item in the Documents folder…begin by starting the Ruby interactive interpreter , following by the necessary require/include statements (see below) and creating a reference to the Finder application. From Finder, we can make our first request for help, by invoking Finder.help:

Notice there is a property (highlighted above) for a home property, which provides a shortcut to the user’s Home folder. Taking this one step further, let’s request additional help entering Finder.home.help:

Under the list of Elements, notice the reference to folders, which indicates that a folder object has a one-to-many relationship with the file system objects it contains. Using this information, you could now access all the sub-folders of the home folder using the folders element.

Appscript uses the #[] method to specify elements by name, so to get the Documents folder of the Home folder you could use: finder.home.folders['Documents']. Referring again to the help information, we know that we can get the contents (items) of a folder using the items element. Using items will identify all of the folder’s contents. Notice the other options such as files, alias_files, application_files, etc that we can use to identify only certain types of items within a folder.

We can further drill down with the help system to get more information about the items within a folder using finder.home.folders['Documents'].items.help, as shown below:

Notice we can now access an items name, extension, among other properties. We began with the intention to get the name of every item in the Document folders, and with the last help statement, we now have all the information we need. The full rb-appscript statement looks like this: finder.home.folders['Documents'].items.name.get

You can read more about the help system in the rb-appscript manual.

Additional posts in the series: Part 1, Part 2, Part 3, Part 4, Part 5

In the previous posts on rb-appscript I dug into some code to show how you can use Ruby and rb-appscript to accomplish the same tasks available with AppleScript. Let’s take a few steps back to look closer at some of the workings behind AppleScript, which is important to understand if you want to begin any serious work regardless of the scripting language you choose.

The Open Scripting Architecture (OSA) is designed to allow for automating tasks, inter-application communication and otherwise directing application behavior. Apple events are the backbone of OSA, facilitating messaging and interaction with applications (think interprocess communication).
Read more »

If you spend any amount of time working with Ruby in the interactive shell (irb), what follows is a handy script for adding command completion support as well as command history across irb sessions.

Read more »

There are just two days left in the Call for Papers for the Rails Europe 2008 conference. The final deadline for papers is midnight on March 18th, 2008!

Read more »

My intention in starting this series of posts on Ruby was to re-write two short AppleScript applications; one that turns down the volume at shutdown, and one that resets the volume upon bootup. We’ve covered enough information up to this point to have all we need to write the Ruby version (using rb-appscript).
Read more »