<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mac Developer Tips &#187; Ruby</title>
	<atom:link href="http://MacDeveloperTips.com/category/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://MacDeveloperTips.com</link>
	<description>Tips, tools and code for iPhone and Mac developers.</description>
	<lastBuildDate>Tue, 29 Jun 2010 19:58:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Using a String as a File in Ruby</title>
		<link>http://MacDeveloperTips.com/ruby/using-a-string-as-a-file-in-ruby.html</link>
		<comments>http://MacDeveloperTips.com/ruby/using-a-string-as-a-file-in-ruby.html#comments</comments>
		<pubDate>Tue, 03 Jun 2008 13:37:41 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[string]]></category>

		<guid isPermaLink="false">http://MacDeveloperTips.com/ruby/using-a-string-as-a-file-in-ruby.html</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>In the lines below, the code after the <font color="#800000"><em>#=&gt;</em></font> 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.</p>
<pre>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 # =&gt; "This is a test of a string as a file. \r\n"

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

# Seek to new position and read 7 more characters
str.pos = 59  # =&gt; 59
str.read(7) # =&gt; "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 # =&gt; "Here's how to use a string as a file.
     \r\n And this could be another line in the file"
str.eof? # =&gt; true</pre>
<p>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:</p>
<pre>
  some_method(StringIO.new("Your string here"))</pre>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/using-a-string-as-a-file-in-ruby.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using a Stack with Ruby</title>
		<link>http://MacDeveloperTips.com/ruby/using-a-stack-with-ruby.html</link>
		<comments>http://MacDeveloperTips.com/ruby/using-a-stack-with-ruby.html#comments</comments>
		<pubDate>Tue, 03 Jun 2008 04:01:19 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[stack]]></category>

		<guid isPermaLink="false">http://MacDeveloperTips.com/ruby/using-a-stack-with-ruby.html</guid>
		<description><![CDATA[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 &#8220;formal&#8221; 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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8220;formal&#8221; 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.</p>
<p>We can work around this by creating a simple Stack class as follows:</p>
<pre>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</pre>
<p>Here is how you might use the stack:</p>
<pre>  stack = Stack.new
  stack.push('abc')
  stack.push(100)
  stack.count
  stack.pop()</pre>
<p>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):</p>
<pre>
  def clear
    @the_stack.clear
  end

  def look
    @the_stack.last
  end</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/using-a-stack-with-ruby.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Ruby as AppleScript Alternative &#8211; Part 6</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-6.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-6.html#comments</comments>
		<pubDate>Tue, 25 Mar 2008 12:03:38 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html</guid>
		<description><![CDATA[In this post I&#8217;ll show how to use the interactive help system within rb-appscript to explore the scripting interface for an application. To begin, you&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;ll show how to use the interactive help system within <a href="http://rb-appscript.rubyforge.org/" target="_blank">rb-appscript</a> to explore the scripting interface for an application. To begin, you&#8217;ll need to verify that you have installed ASDictionary version 0.9.0 or later. You can download ASDictionary from <a href="http://sourceforge.net/project/showfiles.php?group_id=175009&amp;package_id=208705" target="_blank">here</a>.</p>
<p>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 <font color="#800000"><em>which ruby</em></font> in a terminal:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-1.png" /></p>
<p>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.</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-2.png" /></p>
<p>The best way to understand how the interactive help works is to go through an example. So, let&#8217;s say that you are interested to get the name of every item in the <font color="#800000"><em>Documents</em></font> folder&#8230;begin by starting the Ruby interactive interpreter , following by the necessary require/include statements (see below) and creating a reference to the <font color="#800000"><em>Finder</em></font> application. From <em><font color="#800000">Finder</font></em>, we can make our first request for help, by invoking <font color="#800000"><em>Finder.help</em></font>:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-3.png" height="383" width="410" /></p>
<p>Notice there is  a property (highlighted above) for a <font color="#800000"><em>home</em></font> property, which provides a shortcut to the user&#8217;s Home folder. Taking this one step further, let&#8217;s request additional help entering <em><font color="#800000">Finder.home.help</font></em>:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-4.png" /></p>
<p>Under the list of Elements, notice the reference to <font color="#800000"><em>folders</em></font>, 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 <font color="#800000"><em>folders</em></font> element.</p>
<p>Appscript uses the <font color="#800000"><em>#[]</em></font> method to specify elements by name, so to get the <em><font color="#800000">Documents</font></em> folder of the <em><font color="#800000">Home</font></em> folder you could use: <em><font color="#800000">finder.home.folders['Documents']</font></em>. Referring again to the help information, we know that we can get the contents (items) of a folder using the <em><font color="#800000">items</font></em> element. Using <font color="#800000"><em>items</em></font> will identify all of the folder&#8217;s contents. Notice the other options such as <em><font color="#800000">files</font></em>, <em><font color="#800000">alias_files</font></em>, <font color="#800000"><em>application_files</em></font>, etc that we can use to identify only certain types of items within a folder.</p>
<p>We can further drill down with the help system to get more information about the items within a folder using <font color="#800000"><em>finder.home.folders['Documents'].items.help</em></font>, as shown below:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-6.png" /></p>
<p>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 <font color="#800000"><em>Document</em></font> folders, and with the last help statement, we now have all the information we need. The full rb-appscript statement looks like this:  <font color="#800000"><em>finder.home.folders['Documents'].items.name.get</em></font></p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asd-7.png" /></p>
<p>You can read more about the help system in the <a href="http://appscript.sourceforge.net/rb-appscript/doc/appscript-manual/04_gettinghelp.html" target="_blank">rb-appscript manual</a>.</p>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html" target="_blank">Part 3</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank">Part 4</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html" target="_blank">Part 5</a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-6.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ruby as AppleScript Alternative &#8211; Part 5</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-5.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-5.html#comments</comments>
		<pubDate>Mon, 24 Mar 2008 13:02:34 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html</guid>
		<description><![CDATA[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&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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.</p>
<p>The <a href="http://developer.apple.com/documentation/AppleScript/Conceptual/AppleScriptX/Concepts/osa.html" target="_blank">Open Scripting Architecture</a> (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).<br />
<span id="more-92"></span><br />
The structure of an application or a document is defined through the Apple event object model. When an application implements this object model, that application is then considered scriptable, which means you can communicate with the application using AppleScript, rb-appscript or other scripting languages that are OSA compliant.</p>
<p>In regards to the object model, <font color="#800000"><em>elements</em></font> refer to attributes such as the paragraphs or words of a document. Elements can be referred to by numerical position or, if they have &#8216;name&#8217; properties, by name. Objects also have <font color="#800000"><em>properties</em></font>, which can hold either a simple attribute (name, position, etc.), or a reference to another application object. An important distinction is that there can be any number of elements (e.g. paragraphs, words, etc) whereas a property has only one defined value (e.g. version number).</p>
<p>The figure below shows the relationships of elements and properties and is from the paper  <a href="http://www.cs.utexas.edu/users/wcook/papers/AppleScript/AppleScript95.pdf" target="_blank">The Open Scripting Architecture: Automating, Integrating, and Customizing Application</a> by Cook and Harris, 1993.<br />
<img src="http://macdevelopertips.com/wp-content/uploads/2008/03/osa.png" />.</p>
<p>As an example of a property that includes a reference to another object, the <font color="#800000"><em>text</em></font> property of the TextEdit application contains a text object, which includes character, word and paragraph elements. Each of these elements can be accessed using various commands as shown in the examples below:</p>
<pre>
# Set text color
tedit = app('TextEdit')
tedit.documents[1].text.paragraphs.color.set('blue')

# New paragraph at the end of the document
tedit.make(:new =&gt; :paragraph,
                :with_data =&gt;
                "New content here...", :at =&gt;
                tedit.documents[1].text.paragraphs.end)</pre>
<p>Using <font color="#800000"><em>commands</em></font> we can interact with objects using rb-appscript. Applications generally support the commands: run, launch, activate, reopen, open, print and quit. Depending on the application, there may be any number of additional commands that are available. For example, TextEdit offers the &#8216;make&#8217; command (shown above) that can be used to make a new paragraph, create a new document, etc.</p>
<p>Let&#8217;s wrap up by showing a few examples. Enter the following commands using <font color="#800000"><em>irb</em></font> :</p>
<pre>
#1 Begin by importing the appscript module:
require "appscript"
include Appscript

#2 - Create an new object specifying the application we want to target
tedit = app('TextEdit')

#3 - Create a new document using make command:
doc = tedit.make(:new =&gt; :document)

#4 - Set the content of the document:
tedit.set(doc.text, :to =&gt; 'First paragraph')

#5 - Set text color
tedit.documents[1].text.paragraphs.color.set('blue')

#6 - Get the document text
text = tedit.get(doc.text)

#7 - Show text
puts text</pre>
<p>The TextEdit document should look as follows when you are done:<img src="http://macdevelopertips.com/wp-content/uploads/2008/03/irb-output.png" /></p>
<p>Hopefully this post has provided a little more insight as to the object model and working with elements, properties and commands. In the next post I&#8217;ll show how to use the interactive help built into rb-appscript.</p>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html" target="_blank">Part 3</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank">Part 4</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html" target="_blank">Part 6</a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-as-applescript-alternative-part-5.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby irb Command History</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-irb-command-history.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-irb-command-history.html#comments</comments>
		<pubDate>Mon, 17 Mar 2008 23:33:20 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-irb-command-history.html</guid>
		<description><![CDATA[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. require 'irb/completion' require 'irb/ext/save-history' ARGV.concat [ "--readline", "--prompt-mode", "simple" ] # 25 entries in the list IRB.conf[:SAVE_HISTORY] = 25 # Store [...]]]></description>
			<content:encoded><![CDATA[<p>If you spend any amount of time working with Ruby in the interactive shell (<em><font color="#800000">irb</font></em>), what follows is a handy script for adding command completion support as well as command history across irb sessions.</p>
<p><span id="more-77"></span></p>
<pre>
require 'irb/completion'
require 'irb/ext/save-history'

ARGV.concat [ "--readline",
              "--prompt-mode",
              "simple" ]

# 25 entries in the list
IRB.conf[:SAVE_HISTORY] = 25

# Store results in home directory with specified file name
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"</pre>
<p>The reference to <em>SAVE_HISTORY</em> is how many commands you want to store in the history list and the <em>HISTORY_FILE</em> is the name of the file where the commands are stored. Save the file as <font color="#800000"><em>~/.irbrc</em></font>  (in your home directory with the name .irbrc).</p>
<p>Below I&#8217;ve enter several commands using <font color="#800000"><em>irb</em></font>. I used command completion (hitting tab key twice) on the line that begins with &#8220;a.p&#8221; and you can see how command completion shows the available options (a.pack, a.parition, etc).</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/irb1.png" /></p>
<p>Once I quite the <font color="#800000"><em>irb</em></font> session and open the .irb_history file  it will look as follows:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/irb2.png" /></p>
<p>Now, if I start a new <font color="#800000"><em>irb</em></font> session the commands in the history file be available by pressing the up arrow (not unlike the history available in a Terminal window). Although this configuration option is nothing new for those who been working with Ruby, it warrants mentioning for anyone who is just getting started with Ruby.</p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-irb-command-history.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby, an AppleScript Alternative &#8211; Part 4</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-4.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-4.html#comments</comments>
		<pubDate>Sat, 15 Mar 2008 03:44:33 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[AppleScript]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html</guid>
		<description><![CDATA[The fourth in a series of posts on how to use Ruby (rb-appscript) as a replacement for AppleScript.]]></description>
			<content:encoded><![CDATA[<p>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&#8217;ve covered enough information up to this point to have all we need to write the Ruby version (using rb-appscript).<br />
<span id="more-68"></span></p>
<p>The AppleScript example we are porting to Ruby is as follows:</p>
<pre>tell application "Finder"

display dialog "What would you like to do?"
   buttons {"Shutdown", "Restart", "Cancel"} default button "Cancel"
  with icon caution

if button returned is "Shutdown" then
  set volume 0
  shut down
else if button returned is "Restart" then
  set volume 0
  restart
end if

end tell</pre>
<p>Pretty simple application, display a dialog box with three options and based on the selected option, shut down the system, go to sleep or do nothing. The application to reset the volume at boot time is all of one line:</p>
<pre>set volume 5</pre>
<p>You can get the specifics of how I used these scripts by referring back to the <a href="http://macdevelopertips.com/applescript/lower-volume-and-shutdown.html">original post</a>.</p>
<p>The Ruby version of the first script looks as follows:</p>
<pre>require 'osax'
include OSAX

# Display dialog box and get user request
dialog = osax.display_dialog( "What would you like to do?",
  :buttons =&gt; ["Shutdown", "Restart", "Cancel "], :default_button =&gt; "Cancel ",
  :with_title =&gt; "System Shutdown...", :with_icon =&gt; :caution)

if dialog[:button_returned] == "Shutdown"
  puts "Shutdown"
  osax.set_volume(0)
  app("System Events").shut_down()
elsif dialog[:button_returned] == "Restart"
  puts "Restart"
  osax.set_volume(0)
  app("System Events").restart()
end</pre>
<p>The Ruby code to reset the volume is as simple as its AppleScript counterpart:</p>
<pre>require 'osax'
include OSAX

# Turn volume up (range is 0 to 7)
osax.set_volume(5)</pre>
<p>One caveat worth mentioning regarding the Ruby code: notice there is space in the references to &#8220;Cancel &#8221; &#8211; You can read why that is by following <a href="http://rubyforge.org/pipermail/rb-appscript-discuss/2008-January/000107.html" target="_blank">this thread</a> on the rb-appscript discussion/mailing list.</p>
<p><strong><font color="#000080"> Additional Resources:</font></strong></p>
<p>I&#8217;ll leave you with a few additional resources that should be helpful if you are new to rb-appscript and/or AppleScript:</p>
<ul>
<li><a href="http://appscript.sourceforge.net/rb-appscript/doc/index.html" target="_blank">Documentation on rb-appscript </a></li>
<li><a href="http://appscript.sourceforge.net/rb-appscript/doc/appscript-manual/03_quicktutorial.html" target="_blank">Tutorial on getting started with rb-appscript</a></li>
<li><a href="http://appscript.sourceforge.net/links.html" target="_blank">Additional links</a></li>
</ul>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html" target="_blank">Part 3</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html" target="_blank">Part 5</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html" target="_blank">Part 6</a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-4.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby, an AppleScript Alternative &#8211; Part 3</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-3.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-3.html#comments</comments>
		<pubDate>Fri, 14 Mar 2008 01:36:07 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[AppleScript]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html</guid>
		<description><![CDATA[This post is 3rd in a series about using Ruby and rb-appscript as an alternative to AppleScript.]]></description>
			<content:encoded><![CDATA[<p>So enough of the introductions (see <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a> and <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>), let&#8217;s get on with the code. To get started, let&#8217;s look at how to use scripting additions from within rb-appscript as the application that I have in mind will need to display a dialog box (which is located in Standard Additions). We can get a list of the additions currently available as well as a list of commands using the following Ruby code:<br />
<span id="more-57"></span></p>
<pre>
require 'osax'
include OSAX

# List available scripting additions
puts osax.scripting_additions

puts "~~~~~~~~~~"

# List all commands:
puts osax.commands</pre>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/ruby-cmd.png" height="411" width="302" /></p>
<p>Notice the third line from the top, StandardAdditions, this is the addition I&#8217;m after. Let&#8217;s take this one step further and view the rb-appscript variation of a dictionary. rb-appscript includes a tool, <a href="http://appscript.sourceforge.net/tools.html" target="_blank">ASDictionary</a>, which will export to text or HTML (I recommend the HTML with frames option) information on scriptable applications.</p>
<p>Not unlike the dictionary available in the Script Editor, ASDictionary will list the suites, classes and commands, however, the content is tailored for use with specifically with rb-appscript and Ruby. The screenshot below shows the StandardAdditions library information from with ASDictionary.</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/asdic.png" /></p>
<p>Now, contrast the above image with the image below, which is the Standard Additions dictionary shown yesterday (for AppleScript).</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/dict-dialog.png" height="333" width="462" /></p>
<p>When working with rb-appscript, you&#8217;ll notice how what would be accessed with AppleScipt as <font color="#800000"><em>display dialog</em></font> is requested using <em><font color="#800000">display_dialog(&#8230;)</font></em> in rb-appscript.</p>
<p>As a more complete example, the code below will show a dialog box using AppleScript:</p>
<pre>
display dialog "What would you like to do?" buttons {"Shutdown", "Restart", "Cancel"}
   default button "Shutdown" with icon caution</pre>
<p>Here is the same code written using Ruby:</p>
<pre>
osax.display_dialog( "What would you like to do?", :buttons =&gt; [ "Shutdown", "Restart", "Cancel " ],
  :default_button =&gt; "Shutdown", :with_icon =&gt; :caution)</pre>
<p>Regardless of the approach, the end result of the either code block above looks the same:</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/shutdown1.png" align="right" /></p>
<p>This is a good time to point you at the <a href="http://appscript.sourceforge.net/rb-appscript/doc/index.html" target="_blank">documentation for rb-appscript</a> as it covers in great detail all the specifics.</p>
<p>At this point I&#8217;ve covered enough to write something useful. Have a look at the following AppleScript code that I wrote about in a <a href="http://macdevelopertips.com/applescript/lower-volume-and-shutdown.html" target="_blank">previous</a> post.</p>
<pre>tell application "Finder"

display dialog "What would you like to do?"
   buttons {"Shutdown", "Restart", "Cancel"} default button "Shutdown"
  with icon caution

if button returned is "Shutdown" then
  set volume 0
  shut down
else if button returned is "Restart" then
  set volume 0
  restart
end if

end tell</pre>
<p>In an upcoming post I&#8217;ll show to write the same script using using Ruby and rb-appscript. I realize this is a pretty short example, however, if nothing else it should help pull all the pieces together into a working Ruby application that offers an alternative to AppleScript.</p>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank">Part 4</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html" target="_blank">Part 5</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html" target="_blank">Part 6</a><a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-3.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby, an AppleScript Alternative &#8211; Part 2</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-2.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-2.html#comments</comments>
		<pubDate>Thu, 13 Mar 2008 13:30:35 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[AppleScript]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html</guid>
		<description><![CDATA[This is Part 2 in a series on Ruby as an alternative to AppleScript. Introduced are dictionaries and Scripting Additions.]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://macdevelopertips.com/applescript/applescript-20-language-guide.html" target="_blank">Part 1 of this series</a> I walked through the steps to install <a href="http://appscript.sourceforge.net/rb-appscript/index.html" target="_blank">rb-appscript</a>, a scripting bridge that provides an alternative to AppleScript for controlling scriptable applications on a Mac.</p>
<p>My intention in exploring an alternative was to find an option for scripting beyond AppleScript itself and to rewrite an AppleScript program that I was currently using. The original AppleScript code was written to turn down the volume upon shutdown, to enable a silent bootup process. You can read the who, what and why in the <a href="http://macdevelopertips.com/applescript/lower-volume-and-shutdown.html" target="_blank">original post</a>.</p>
<p><span id="more-55"></span>However, I&#8217;m getting ahead of myself. Before we dig into the original code and how to write the same application in Ruby, let me take some time to explain a few other things important concepts within AppleScript.</p>
<p><font color="#003366"><strong>Dictionaries</strong></font></p>
<p>In order to work with a scriptable application (or aspects of the system that are scriptable), one first needs to know what is scritable and how to interact with the scriptable resource, an API of sorts. In AppleScript parlance this is know as the Apple event registry, also referred to as a dictionary.</p>
<p>Let&#8217;s look at a few examples &#8211; to open the dictionary for system related events, open the Script Editor, click on File / Open Dictionary, and browse to the &#8220;System Events.app&#8221; application. Scroll down to the Power Suite and you should see a listing  similar to the Figure below, which shows information on the commands: logout, restart, shutdown and sleep.</p>
<p>Information is organized into suites, which are shown in the leftmost window. In the middle column are available commands for the Power Suite. There is a great deal more information available within the dictionary, however, I&#8217;ll save the detailed description for another day.</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/dict-power.png" /></p>
<p><font color="#003366"><strong>Scripting Additions</strong></font></p>
<p>Scripting Additions are a mechanism for extending the functionality of AppleScript. There are any number of Scripting Additions available (google for scripting additions) from mathematical stuff to sending SMS messages. A good list of addtions can be found at <a href="http://osaxen.com" target="_blank">osaxen.com</a>.</p>
<p>A commonly used Scripting Addition, and one which is included by default, is Standard Additions. For example, to display a dialog box, you use the <font color="#800000"><em>User Interaction Suite</em></font> and the <font color="#800000"><em>display dialog</em></font> command as shown in the figure below. To bring up this dictionary from within the Script Editor, open a new dictionary and scroll to the Standard Additions entry.</p>
<p><img src="http://macdevelopertips.com/wp-content/uploads/2008/03/dict-dialog.png" /></p>
<p>The information covered up to this point will lead us to the next post, which will make it clear why I chose the dictionaries I did in the examples above. And with the next post we&#8217;ll begin to dig into some Ruby code to make a few things happen with Apple Events. Same bat time, same bat channel&#8230;</p>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html" target="_blank">Part 1</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html" target="_blank">Part 3</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank">Part 4</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html" target="_blank">Part 5</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html" target="_blank">Part 6</a><a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-2.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby, an AppleScript Alternative &#8211; Part 1</title>
		<link>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-1.html</link>
		<comments>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-1.html#comments</comments>
		<pubDate>Wed, 12 Mar 2008 22:53:07 +0000</pubDate>
		<dc:creator>john</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[AppleScript]]></category>
		<category><![CDATA[rb-appscript]]></category>

		<guid isPermaLink="false">http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-1.html</guid>
		<description><![CDATA[An introduction and installation guide for rb-appscript to enable Ruby developers to query and control scriptable applications on a Mac, providing an alternative to AppleScript. ]]></description>
			<content:encoded><![CDATA[<p>AppleScript is a scripting language that provides the ability to control &#8220;scriptable&#8221; applications on a Mac. AppleScript provides an interface to the Apple Event messaging architecture, the means by which applications communicate with one another as well as the underlying OS.</p>
<p><span id="more-53"></span>Here is the description of AppleScript from the <a href="http://www.apple.com/applescript/index.html" target="_blank">Apple website</a>:</p>
<blockquote><p>AppleScript is an English-like language used to create script files that control the actions of the computer and the applications that run on it. Much more than just a macro-language, which simply repeats your recorded actions, AppleScript scripts can &#8220;think.&#8221;</p></blockquote>
<p>If you come from a programming background, it may take some time to get used to the &#8220;English-like&#8221; interface. Now this is not necessarily a bad thing as it makes AppleScript more approachable for those without any experience writing code.</p>
<p>In my search for an alternative to AppleScript, I came upon <a href="http://appscript.sourceforge.net/rb-appscript/index.html" target="_blank">rb-appscript</a>. Ruby appscript is an Apple event bridge that provides a framework for querying and controlling scriptable applications from Ruby. I first read about rb-appscript in <a href="http://www.oreilly.com/pub/a/mac/2007/02/27/replacing-applescript-with-ruby.html" target="_blank">this article</a> at O&#8217;Reilly, which provides an excellent introduction to the topic.</p>
<p>Let&#8217;s walk through how to install rb-appscript and wrap up with a short Ruby script to verify everything is working. For installation, there are two options &#8211; one is via RubyGems, the second is to build from source. I generally build from source as I have more control over the process. The steps for doing so are shown below (you&#8217;ll find the same basic steps listed in the O&#8217;Reilly article mentioned above):</p>
<ol>
<li>Download rb-appscript from <a href="http://rubyforge.org/projects/rb-appscript/" target="_blank">RubyForge</a> (I am running rb-appscript-0.5.1)</li>
<li>Extract the contents of the zip file</li>
<li>From the directory where the files were extracted, run these commands from a Terminal:</li>
<p>&gt; <font color="#800000"><em>ruby extconf.rb</em></font><br />
&gt; <font color="#800000"><em>make</em></font><br />
&gt; <font color="#800000"><em>sudo make install</em></font></p>
<li>Open a text file and enter the following code:</li>
<pre>
require "appscript"
include Appscript

app('TextEdit').activate</pre>
<li> Save the file as <font color="#800000"><em>test.rb</em></font> and from a Terminal run the script:<br />
&gt; <em><font color="#800000">ruby test.rb</font></em></li>
</ol>
<p>This short application does nothing more then use an application object to activate TextEdit, bringing it to the foreground (starting it if necessary). If all is well, you should see TextEdit as the top most application.</p>
<p>In the next tip I&#8217;ll dig a little deeper into working with rb-appscript, including a look at how to access Standard Additions such as dialog boxes.</p>
<p>Additional posts in the series: <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-2.html" target="_blank">Part 2</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-3.html" target="_blank">Part 3</a>, <a href="http://macdevelopertips.com/ruby/ruby-an-applescript-alternative-part-4.html" target="_blank">Part 4</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-5.html" target="_blank">Part 5</a>, <a href="http://macdevelopertips.com/ruby/ruby-as-applescript-alternative-part-6.html" target="_blank">Part 6</a></p>
]]></content:encoded>
			<wfw:commentRss>http://MacDeveloperTips.com/ruby/ruby-an-applescript-alternative-part-1.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
