<?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>A Twofer</title>
	<atom:link href="http://www.atwofer.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.atwofer.com</link>
	<description>A place to talk about Software Development (RoR, J2EE, J2ME, CSS, HTML, JavaScript, Objective-C, etc) and some other stuff</description>
	<lastBuildDate>Thu, 04 Mar 2010 19:29:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Single Table Inheritance and accepts_nested_attributes_for</title>
		<link>http://www.atwofer.com/2009/11/02/single-table-inheritance-and-accepts_nested_attributes_for/</link>
		<comments>http://www.atwofer.com/2009/11/02/single-table-inheritance-and-accepts_nested_attributes_for/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 00:42:36 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[accepts_nested_attributes_for]]></category>
		<category><![CDATA[STI]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=129</guid>
		<description><![CDATA[I recently upgraded our web app at Episodic from Rails 2.0 to Rails 2.3.4.  While this resulted in many issues we had to resolve that I will try to write about in later post, it does allow me to take advantage of some of the Rails 2.3.x features like accepts_nested_attributes_for.  If you aren’t [...]]]></description>
			<content:encoded><![CDATA[<p>I recently upgraded our web app at <a href="http://www.episodic.com">Episodic</a> from Rails 2.0 to Rails 2.3.4.  While this resulted in many issues we had to resolve that I will try to write about in later post, it does allow me to take advantage of some of the Rails 2.3.x features like accepts_nested_attributes_for.  If you aren’t familiar with accepts_nested_attributes_for then check out <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">Ryan’s post</a>.</p>
<p>So I went ahead and tried to make use of this in my object model.  Here are the important parts of the model.</p>
<p><code><br />
<span>class Episode < ActiveRecord::Base</span><br />
<span style="padding-left: 20px">has_many :field_values, :dependent => :destroy</span><br />
<span style="padding-left: 20px">accepts_nested_attributes_for :field_values, :allow_destroy => true</span><br />
<span>end</span><br />
<span></span><br />
<span>class FieldValue < ActiveRecord::Base</span><br />
<span style="padding-left: 20px">:belongs_to :episode</span><br />
<span>end</span><br />
<span></span><br />
<span>class TextFieldValue < FieldValue</span><br />
<span>end</span><br />
<span></span><br />
<span>class NumberFieldValue < FieldValue</span><br />
<span>end</span><br />
</code></p>
<p>Since I am using Single Table Inheritance I end up with a field_values table that has a column named “type” which contain either a value of “TextFieldValue” or “NumberFieldValue”.</p>
<p>Also, because I enabled accepts_nested_attributes_for on my Episode class I should be able to do something like:</p>
<p><code><br />
<span>episode.field_values_attributes = </span><br />
<span style="padding-left: 20px">[{:value => “foo”, :type => “TextFieldValue”}]</span><br />
</code></p>
<p>However, when I look in the DB I see that there is a new row but the “type” column is NULL even though I set it to “TextFieldValue”.  When I look in the logs I see: &#8220;Can&#8217;t mass-assign these protected attributes: type&#8221;.</p>
<p>Luckily, there is a way around this.  I added a setter called &#8220;value_type&#8221; to my FieldValue class.</p>
<p><code><br />
<span>def value_type= value_type</span><br />
<span style="padding-left: 20px">self.type = value_type</span><br />
<span>end</span><br />
</code></p>
<p>Now, when I can safely use field_values_attributes and set a type.</p>
<p><code><br />
<span>episode.field_values_attributes = </span><br />
<span style="padding-left: 20px">[{:value => “foo”, :value_type => “TextFieldValue”}]</span><br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/11/02/single-table-inheritance-and-accepts_nested_attributes_for/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling redirects with initWithContentURL</title>
		<link>http://www.atwofer.com/2009/08/13/handling-redirects-with-initwithcontenturl/</link>
		<comments>http://www.atwofer.com/2009/08/13/handling-redirects-with-initwithcontenturl/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 17:00:03 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[MPMoviePlayerController]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[iPhone SDK]]></category>
		<category><![CDATA[head request]]></category>
		<category><![CDATA[initWithContentURL]]></category>
		<category><![CDATA[initWithURL]]></category>
		<category><![CDATA[NSURLConnection]]></category>
		<category><![CDATA[redirect]]></category>
		<category><![CDATA[Redirects]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=118</guid>
		<description><![CDATA[I keep running into this problem so I thought that I should post my solution.  There are some classes in the iPhone SDK like the MPMoviePlayerController that have an initWithContentURL method. However, the problem is that the URL I have is one that may issue a redirect response when requested.  When I provide [...]]]></description>
			<content:encoded><![CDATA[<p>I keep running into this problem so I thought that I should post my solution.  There are some classes in the iPhone SDK like the MPMoviePlayerController that have an initWithContentURL method. However, the problem is that the URL I have is one that may issue a redirect response when requested.  When I provide such a URL to initWithContentURL the player tells me that it cannot play me file.  To work around this problem I wrote some very simple code.</p>
<p>The first thing you need to do is to build a HEAD request using NSMutableURLRequest.  Then create an NSURLConnection settings the delegate as the current instance.</p>
<p><code><br />
<span>NSMutableURLRequest *headRequest = </span><br />
<span style="padding-left: 40px">[NSMutableURLRequest requestWithURL:resourceURL</span><br />
<span style="padding-left: 40px">cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];</span><br />
<span> </span><br />
<span style="padding-left: 0px">[headRequest setHTTPMethod:@"HEAD"];</span><br />
<span> </span><br />
<span style="padding-left: 0px">connection = [[NSURLConnection alloc] </span><br />
<span style="padding-left: 40px">initWithRequest:headRequest delegate:self];</span><br />
</code></p>
<p>Now we just need to implement the delegate method to play the URL from the response.</p>
<p><code><br />
<span style="padding-left: 0px">- (void)connection:(NSURLConnection *)connection </span><br />
<span style="padding-left: 40px">didReceiveResponse:(NSURLResponse *)response {</span><br />
<span> </span><br />
<span style="padding-left: 20px">// Now we have resolved the URL so play the movie</span><br />
<span style="padding-left: 20px">thePlayer = [[MPMoviePlayerController alloc] </span><br />
<span style="padding-left: 40px">initWithContentURL:[response URL]];</span><br />
<span> </span><br />
<span style="padding-left: 20px">[thePlayer play];</span><br />
<span style="padding-left: 0px">}</span><br />
</code></p>
<p>Obviously, this example handles one redirect but you can see that you can easily have it loop and until [response statusCode] == 200.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/08/13/handling-redirects-with-initwithcontenturl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Streaming and playing fixed-length MP3s using the iPhone SDK</title>
		<link>http://www.atwofer.com/2009/06/30/streaming-and-playing-fixed-length-mp3s-using-the-iphone-sdk/</link>
		<comments>http://www.atwofer.com/2009/06/30/streaming-and-playing-fixed-length-mp3s-using-the-iphone-sdk/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 22:49:34 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[Audio Queue Services]]></category>
		<category><![CDATA[AudioStreamer]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[iPhone SDK]]></category>
		<category><![CDATA[MPMoviePlayerController]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=100</guid>
		<description><![CDATA[The Problem
Lately, I&#8217;ve been doing a fair amount of coding using Objective-C and the iPhone SDK.  Once I got used to the language I really started to like it.  The more I used the SDK the more impressed I became with how much I could do with it.  However, when a customer [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Problem</strong></p>
<p>Lately, I&#8217;ve been doing a fair amount of coding using Objective-C and the iPhone SDK.  Once I got used to the language I really started to like it.  The more I used the SDK the more impressed I became with how much I could do with it.  However, when a customer of ours at <a href="http://www.episodic.com" target="_blank">Episodic</a> needed an iPhone App that could play a list of MP3s (RSS Feed to be exact) with &#8220;iPod-like&#8221; functionality, I was surprised to find that this is not something I can do with the embedded Quicktime Player.  In fact, you can&#8217;t even just hook into the <em>MPMoviePlayerController</em>.  For example, there is no way to know when one songs ends so that I can start the next song since the <em>MPMoviePlayerPlaybackDidFinishNotification</em> notification is fired when the song ends or the user hits the done button.  So after a lot of searching I came across Matt Gallagher&#8217;s great post &#8220;<a href="http://cocoawithlove.com/2009/06/revisiting-old-post-streaming-and.html" target="_blank">Revisiting an old post: Streaming and playing an MP3 stream</a>&#8220;.</p>
<p><strong>Modifying the AudioStreamer Class to Play Fixed-Length MP3s</strong></p>
<p>So Matt&#8217;s post got me part of the way there.  It at least gave me an understanding of the tools I would need to use to accomplish my task.  The main difference between what he had and what I needed is that he was playing an MP3 stream and I wanted to play MP3 files.  The first change I made was I added a new constructor to the AudioStreamer class.  This allowed me to initialized the class with a URL to a file on the file system (I&#8217;ll talk about how to get the file on your file system later).</p>
<p><code><span style="padding-left:20px;">- (id)initWithFileURL:(NSURL *)aURL {</span><br />
<span style="padding-left:40px;">[self initWithURL:aURL];</span><br />
<span style="padding-left:40px;">fixedLength = YES;</span><br />
<span style="padding-left:40px;">return self;</span><br />
<span style="padding-left:20px;">}</span></code></p>
<p>This constructor sets a flag to indicate that we are streaming fixed-length MP3s.  I then key off this flag in the <em>openFileStream</em> method.</p>
<p><code><span style="padding-left:20px;">if (fixedLength) {</span><br />
<span style="padding-left:40px;">stream = CFReadStreamCreateWithFile(</span><br />
<span style="padding-left:80px;">kCFAllocatorDefault, (CFURLRef)url);</span><br />
<span style="padding-left:20px;">} else {</span><br />
<span style="padding-left:40px;">CFHTTPMessageRef message = CFHTTPMessageCreateRequest(</span><br />
<span style="padding-left:80px;">NULL, (CFStringRef)@"GET", (CFURLRef)url, kCFHTTPVersion1_1);</span><br />
<span style="padding-left:40px;">stream = CFReadStreamCreateForHTTPRequest(NULL, message);</span><br />
<span style="padding-left:40px;">CFRelease(message);</span><br />
<span style="padding-left:40px;">...</span></code></p>
<p>The above code simply creates the stream from the file system instead of a remote file.  Because the result is still a CFReadStreamRef object the rest of the class mostly remains unchanged.</p>
<p><strong>Downloading the MP3</strong></p>
<p>In my controller I just need to download the MP3 file to a location on the file system.  This can be done very easily by using a combination of <em>NSURLConnection</em> and <em>NSFileHandle</em>.</p>
<p><code><span style="padding-left:20px;">audioFile = [[NSFileHandle</span><br />
<span style="padding-left:60px;">fileHandleForWritingAtPath:downloadFileName] retain];</span><br />
<span style="padding-left:20px;">NSURLRequest *downloadRequest = [NSURLRequest</span><br />
<span style="padding-left:60px;">requestWithURL:resourceURL </span><br />
<span style="padding-left:60px;">cachePolicy:NSURLRequestUseProtocolCachePolicy</span><br />
<span style="padding-left:60px;">timeoutInterval:60.0]; </span><br />
<span style="padding-left:20px;">download = [[NSURLConnection alloc]</span><br />
<span style="padding-left:60px;">initWithRequest:downloadRequest delegate:self];</span></code></p>
<p>This code creates the file to write the data to and creates the connection to fetch the data.  I know just need to handle the data.</p>
<p><code><span style="padding-left:20px;">- (void)connection:(NSURLConnection *)connection </span><br />
<span style="padding-left:60px;">didReceiveData:(NSData *)data {</span><br />
<span style="padding-left:40px;">// Append the data to the file on the file system</span><br />
<span style="padding-left:40px;">[audioFile writeData:data];</span><br />
<span style="padding-left:40px;">downloadedLength += [data length];</span><br />
<span style="padding-left:40px;"> </span><br />
<span style="padding-left:40px;">// When we get enough of the file, then just start playing it.</span><br />
<span style="padding-left:40px;">if (!streamer &amp;&amp; downloadedLength &gt; DEFAULT_MIN_LENGTH_TO_PLAY) {</span><br />
<span style="padding-left:60px;">NSLog(@"start playback for %@", downloadFileName);</span><br />
<span style="padding-left:60px;">[self initAndStartStreamer];</span><br />
<span style="padding-left:40px;">}</span><br />
<span style="padding-left:20px;">}</span></code></p>
<p>The above code is the <em>NSURLConnection</em> delegate method for receiving the data and writing the data to the file.  Once I have &#8220;enough&#8221; of the MP3 I can start playing it by create the streamer and passing it the URL to our <em>audioFile</em>.</p>
<p><strong>NEW: Handling EOF</strong></p>
<p>One bug that I ran into since my initial post is that if I actually put this on my phone and went outside, away from my wireless network, the song would sometimes end early.  What was happening is that the AudioStreamer was playing the file faster than it was being downloaded.  The AudioStreamer would hit the EOF and then stop.  To prevent this case I added some &#8220;throttling&#8221; to the playback loop that checks if we are too close to the end of the file and changes the state to buffering until we have enough to continue.  The following code is in startInternal.</p>
<p><code><span style="padding-left:20px;">// Flag to indicate that we have gotten too close to the EOF before the</span><br />
<span style="padding-left:20px;">//  entire file has downloaded so we need throttle the playback.</span><br />
<span style="padding-left:20px;">BOOL isThrottling = NO;{</span><br />
<span> </span><br />
<span style="padding-left:20px;">//</span><br />
<span style="padding-left:20px;">// Process the run loop until playback is finished or failed.</span><br />
<span style="padding-left:20px;">//</span><br />
<span style="padding-left:20px;">BOOL isRunning = YES;</span><br />
<span style="padding-left:20px;">do</span><br />
<span style="padding-left:20px;">{</span><br />
<span style="padding-left:40px;">// If we are playing a fixed-length MP3 make sure we are not too close</span><br />
<span style="padding-left:40px;">// to the end of the file. This prevents us from hitting the end of</span><br />
<span style="padding-left:40px;">// the file. before it is fully downloaded.  Very useful when not on</span><br />
<span style="padding-left:40px;">// 3G since the song may be played faster than it is downloaded.</span><br />
<span style="padding-left:40px;">if (!fixedLength || self.fileDownloadComplete || </span><br />
<span style="padding-left:80px;">self.fileDownloadCurrentSize &gt; (fileDownloadBytesRead + </span><br />
<span style="padding-left:80px;">(kAQBufSize * kNumAQBufs))) {</span><br />
<span> </span><br />
<span style="padding-left:60px;">isRunning = [[NSRunLoop currentRunLoop</span><br />
<span style="padding-left:100px;">runMode:NSDefaultRunLoopMode</span><br />
<span style="padding-left:100px;">beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]];</span><br />
<span> </span><br />
<span style="padding-left:60px;">if (isThrottling) {</span><br />
<span style="padding-left:80px;">isThrottling = NO;</span><br />
<span style="padding-left:80px;">AudioQueueStart(audioQueue, NULL);</span><br />
<span style="padding-left:80px;">self.state = AS_PLAYING;</span><br />
<span style="padding-left:60px;">}</span><br />
<span style="padding-left:60px;"> </span><br />
<span style="padding-left:60px;">//</span><br />
<span style="padding-left:60px;">// If there are no queued buffers, we need to check here since the</span><br />
<span style="padding-left:60px;">// handleBufferCompleteForQueue:buffer: should not change the state</span><br />
<span style="padding-left:60px;">// (may not enter the synchronized section).</span><br />
<span style="padding-left:60px;">//</span><br />
<span style="padding-left:60px;">if (buffersUsed == 0 &amp;&amp; self.state == AS_PLAYING)</span><br />
<span style="padding-left:60px;">{</span><br />
<span style="padding-left:80px;">self.state = AS_BUFFERING;</span><br />
<span style="padding-left:60px;">}</span><br />
<span style="padding-left:40px;">} else if (!isThrottling &amp;&amp; self.state == AS_PLAYING) {</span><br />
<span style="padding-left:60px;">NSLog(@"Start throttling because we are too close to EOF.");<br />
<span style="padding-left:60px;"> </span><br />
<span style="padding-left:60px;">self.state = AS_BUFFERING;</span><br />
<span style="padding-left:60px;"> </span><br />
<span style="padding-left:60px;">AudioQueuePause(audioQueue);</span><br />
<span style="padding-left:60px;">isThrottling = YES;</span><br />
<span style="padding-left:60px;"> </span><br />
<span style="padding-left:60px;">// Sleep for a few seconds</span><br />
<span style="padding-left:60px;">[NSThread sleepForTimeInterval:3.0];</span><br />
<span style="padding-left:40px;">}</span><br />
<span style="padding-left:40px;"> </span><br />
<span style="padding-left:20px;">} while (isRunning &amp;&amp; ![self runLoopShouldExit]);</span><br />
</span></code></p>
<p><strong>Seeking?</strong></p>
<p>I was unable to figure out a way to allow for seeking. This would also provide a way for playback to pick up where it left off when the connection during the download phase.  If anyone has ideas on how to support this I would love to hear about it.</p>
<p><strong>Conclusion</strong></p>
<p>This is still far from ideal and it really seems like this is something that should be a lot easier to do within the SDK.  In the meantime, hopefully this is helpful to others.</p>
<p>You can download my source code <a title="Source Code" href="http://www.atwofer.com/wp-content/uploads/2009/06/FixedLengthPlayer-v2.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/06/30/streaming-and-playing-fixed-length-mp3s-using-the-iphone-sdk/feed/</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
		<item>
		<title>Getting the errorID from an ErrorEvent in ActionScript</title>
		<link>http://www.atwofer.com/2009/02/24/getting-the-errorid-from-an-errorevent-in-actionscript/</link>
		<comments>http://www.atwofer.com/2009/02/24/getting-the-errorid-from-an-errorevent-in-actionscript/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 04:15:29 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[ErrorEvent]]></category>
		<category><![CDATA[ErrorEvent.errorID]]></category>
		<category><![CDATA[FlashPlayer]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=85</guid>
		<description><![CDATA[Our Episodic Video Player is written in ActionScript 3.  I&#8217;m still fairly new to ActionScript but came up with a solution to a problem the other day that I thought I should share.
The player loads various files from the server.  In some cases I want to display an error when one of those [...]]]></description>
			<content:encoded><![CDATA[<p>Our <a href="http://www.episodic.com/" target="_blank">Episodic Video Player</a> is written in ActionScript 3.  I&#8217;m still fairly new to ActionScript but came up with a solution to a problem the other day that I thought I should share.</p>
<p>The player loads various files from the server.  In some cases I want to display an error when one of those files can&#8217;t be found.  I have an error handler that listens for <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/ErrorEvent.html" target="_blank">Error Events</a> and displays an appropriate error message depending on the type of the error event.  For example, I know that error code 2032 will generally mean in our case that the file could not be found. </p>
<p>Alright, so this all seems simple enough except for one problem.  When I looked at the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/ErrorEvent.html#errorID" target="_blank">ASDocs for ErrorEvent.errorID</a> I noticed that that property is not available for Flash Player 9.  Fortunately, ErrorEvent extends <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/TextEvent.html" target="_blank">TextEvent</a> which has text property I can access.  In the case of an ErrorEvent the text property contains a message that includes the error ID.  Therefore, I just wrote my own getter to grab the error ID.</p>
<p><code>public function get errorID():int {<br />
<span style="padding-left: 10px;">if ((text != null) &#038;&#038; (text.indexOf("Error #") == 0) </span><br />
<span style="padding-left: 40px;">&#038;&#038; (text.length > 7)) {</span><br />
<span style="padding-left: 20px;">// The Error IDs always seem to be 4 digits</span><br />
<span style="padding-left: 20px;">return parseInt(errorEvent.text.substr(7, errorEvent.text.length - 7));</span><br />
}</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/02/24/getting-the-errorid-from-an-errorevent-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Override attribute accessor and before_type_cast</title>
		<link>http://www.atwofer.com/2009/02/17/override-attribute-accessor-and-before_type_cast/</link>
		<comments>http://www.atwofer.com/2009/02/17/override-attribute-accessor-and-before_type_cast/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 03:45:24 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[alias_method]]></category>
		<category><![CDATA[before_type_cast]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=78</guid>
		<description><![CDATA[Our Episodic Video Publishing Web Application is written in Ruby on Rails.  I recently came across a situation where I had a model where I wanted to override it&#8217;s attribute accessors in some cases.  Consider a model that looks like this.
create_table "podcasts", :force =&#62; true do &#124;t&#124;
t.string   "name"
t.boolean  "use_show_name", :default [...]]]></description>
			<content:encoded><![CDATA[<p>Our <a href="http://www.episodic.com/" target="_blank">Episodic Video Publishing Web Application</a> is written in Ruby on Rails.  I recently came across a situation where I had a model where I wanted to override it&#8217;s attribute accessors in some cases.  Consider a model that looks like this.</p>
<p><code>create_table "podcasts", :force =&gt; true do |t|<br />
<span style="padding-left: 10px;">t.string   "name"</span><br />
<span style="padding-left: 10px;">t.boolean  "use_show_name", :default =&gt; true</span><br />
<span style="padding-left: 10px;">t.integer   "show_id"</span><br />
end</code></p>
<p>As you can see above that each podcast belongs to a show.  I also have a form for this model and in the name field I want to display the name of the podcast unless &#8220;use_show_name&#8221; is true then I want to display the name of the show that this podcast belongs to.</p>
<p><code>&lt;%= text_field :podcast, :name, :class =&gt; "text", :disabled =&gt; @podcast.use_show_name %&gt;</code></p>
<p>I don&#8217;t want to put this logic in the ERB template but instead I want to put it in the model so that anyone that calls Podcast.name will get the appropriate value depending on the &#8220;use_show_name&#8221;.</p>
<p><code>class Podcast &lt; ActiveRecord::Base<br />
<span style="padding-left: 10px;">belongs_to :show</span><br />
<span>&nbsp;</span><br />
<span style="padding-left: 10px;">def name</span><br />
<span style="padding-left: 20px;">return self.use_show_name ? self.show.name : read_attribute(:name)</span><br />
<span style="padding-left: 10px;">end</span><br />
<span style="padding-left: 10px;">alias_method :name_before_type_cast, :name</span><br />
end</code></p>
<p>So there a few things going on above.</p>
<ul>
<li>We override the &#8220;name&#8221; method by simply implementing it.  This works because ActiveRecord using method_missing to implement it&#8217;s &#8220;name&#8221; getter but since there is now a &#8220;name&#8221; method, method_missing will not be invoked.</li>
<li>In the method we check &#8220;use_show_name&#8221; to see what value to return.  If it is true we get the value from the show object.  Otherwise, we call read_attribute to get the value of the name attribute that stored in the DB.</li>
<li>Lastly, we alias the name method as &#8220;name_before_type_cast&#8221; since this is the method that is called by FormHelper.text_field.  ActiveRecord form helpers call the before_type_cast so that they can get the string value of the attribute but we want it to get the value from our &#8220;name&#8221; method.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/02/17/override-attribute-accessor-and-before_type_cast/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Prompt User About Unsaved Changes Using Mootools</title>
		<link>http://www.atwofer.com/2009/01/02/prompt-user-about-unsaved-changes-using-mootools/</link>
		<comments>http://www.atwofer.com/2009/01/02/prompt-user-about-unsaved-changes-using-mootools/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 21:41:16 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mootools]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=65</guid>
		<description><![CDATA[Mootools has a very useful method toQueryString on the Form element class.  In short, this method takes all the form fields and builds a query string generally used when sending form data to the server.  However, I found another use for this method that I thought I would share.
For our Episodic Video Publishing Web Application [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mootools.net/docs/" target="_blank">Mootools</a> has a very useful method <a href="http://mootools.net/docs/Element/Element#Element:toQueryString" target="_blank">toQueryString</a> on the Form element class.  In short, this method takes all the form fields and builds a query string generally used when sending form data to the server.  However, I found another use for this method that I thought I would share.</p>
<p>For our <a href="http://www.episodic.com/" target="_blank">Episodic Video Publishing Web Application</a> we have a number of pages that include a form.  If the user tries to navigate from a form that has unsaved changes then we want to prompt the user that they have unsaved changes and that these changes will be lost if they navigate away.  There are various ways that you can detect if the user has modified the page&#8217;s form but the easiest I&#8217;ve found is to make use of <a href="http://mootools.net/docs/Element/Element#Element:toQueryString" target="_blank">Form.toQueryString</a>.</p>
<p>First, create a function that stores the form state in a hidden input.</p>
<p><code>getOrCreateInitialFormState: function(form) {<br />
<span style="padding-left: 10px;">var formInitialState = null;</span>,<br />
<span style="padding-left: 10px;">var formInitialState = $('form_initial_state');</span><br />
<span style="padding-left: 10px;">if (!formInitialState)</span><br />
<span style="padding-left: 20px;">formInitialState = new Element('input', {</span><br />
<span style="padding-left: 20px;">id: 'form_initial_state',</span><br />
<span style="padding-left: 20px;">type: 'hidden',</span><br />
<span style="padding-left: 20px;">value: form.toQueryString()</span><br />
<span style="padding-left: 10px;">}).inject(form, 'before');</span><br />
<span style="padding-left: 10px;">return formInitialState;</span><br />
}</code></p>
<p>So when the page loads record the current form state and hook into the click event for any links on your page and check if the form state has changed.</p>
<p><code>window.addEvent('domready', function()<br />
{<br />
<span style="padding-left: 10px;">// Grab the form</span><br />
<span style="padding-left: 10px;">var form = $('my_form');</span><br />
&nbsp;<br />
<span style="padding-left: 10px;">// Store the form state in a hidden input</span><br />
<span style="padding-left: 10px;">getOrCreateInitialFormState(form);</span><br />
&nbsp;<br />
<span style="padding-left: 10px;">// Capture any clicks that would cause the user to navigate away</span><br />
<span style="padding-left: 10px;">$$('a').addEvent('click', function(e) {</span><br />
<span style="padding-left: 20px;">if (form.toQueryString() != getOrCreateInitialFormState(form) {</span><br />
<span style="padding-left: 30px;">e.stop();</span><br />
<span style="padding-left: 30px;">var result = confirm('You have unsaved changes.' +</span><br />
<span style="padding-left: 50px;">'  Are you sure you want to navigate away from this page?');</span><br />
<span style="padding-left: 30px;">if (result == true) {</span><br />
<span style="padding-left: 40px;">// The user wants to navigate</span><br />
<span style="padding-left: 40px;">window.location.href = a.get('href');</span><br />
<span style="padding-left: 30px;">}</span><br />
<span style="padding-left: 20px;">} </span><br />
<span style="padding-left: 10px;">});</span><br />
});<br />
</code></p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2009/01/02/prompt-user-about-unsaved-changes-using-mootools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using AOP to Make Calls Asynchronous in Java</title>
		<link>http://www.atwofer.com/2008/12/16/using-aop-to-make-calls-asynchronous-in-java/</link>
		<comments>http://www.atwofer.com/2008/12/16/using-aop-to-make-calls-asynchronous-in-java/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 22:39:04 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[MethodInterceptor]]></category>
		<category><![CDATA[MethodInvocation]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=23</guid>
		<description><![CDATA[I am working on a project called ScoreOut that consists of an application that runs on a phone that interacts with a server via a REST API.  The server is written in Java and makes heavy use of the Spring Framework.  I wanted to start tracking some of the actions that a user takes on [...]]]></description>
			<content:encoded><![CDATA[<p>I am working on a project called <a href="http://www.scoreout.com">ScoreOut</a> that consists of an application that runs on a phone that interacts with a server via a REST API.  The server is written in Java and makes heavy use of the <a href="http://www.springframework.org/">Spring Framework</a>.  I wanted to start tracking some of the actions that a user takes on the phone and recording those actions in our analytics tables.  For example, we want to record when a user logs in or requests a golf course.  However, we do not want to slow down the response to the client since the customer is probably out on a golf course at that time.  Therefore, it seemed to makes sense to perform any auditing asynchronously.</p>
<p>The server is broken up into services and I already had a service that did auditing.  I added two new methods to it recordClientLogin and recordCourseRetrieval.  I wanted these methods to be run asynchronously but I wanted the asychronousness (if this isn&#8217;t a word it should be) to be reusable and easily enabled or disabled (easier to unit test when disabled).  This immediately let me to use AOP so I wrote an interceptor.</p>
<p><code><br />
package com.scoreout.service.interceptor;<br />
<span> </span><br />
import org.aopalliance.intercept.MethodInterceptor;<br />
import org.aopalliance.intercept.MethodInvocation;<br />
import org.apache.commons.logging.Log;<br />
import org.apache.commons.logging.LogFactory;<br />
<span> </span><br />
/**<br />
<span style="padding-left:8px;">* Intecepts a call and makes it asynchronous. If there is an error it is</span><br />
<span style="padding-left:8px;">* simply logged.</span><br />
<span style="padding-left:8px;">*/</span><br />
public class AsynchronizeInterceptor implements MethodInterceptor<br />
{<br />
<span> </span><br />
<span style="padding-left:20px;">/**</span><br />
<span style="padding-left:28px;">* Logger</span><br />
<span style="padding-left:28px;">*/</span><br />
<span style="padding-left:20px;">private static final Log LOG = LogFactory.</span><br />
<span style="padding-left:40px;">getLog(AsynchronizeInterceptor.class);</span><br />
<span> </span><br />
<span style="padding-left:20px;">/**</span><br />
<span style="padding-left:28px;">* This method will always return null since the method is</span><br />
<span style="padding-left:28px;">* invoked asynchronously.</span><br />
<span style="padding-left:28px;">*</span><br />
<span style="padding-left:28px;">* @see org.aopalliance.intercept.MethodInterceptor</span><br />
<span style="padding-left:28px;">*          #invoke(org.aopalliance.intercept.MethodInvocation)</span><br />
<span style="padding-left:28px;">*/</span><br />
<span style="padding-left:20px;">public Object invoke(final MethodInvocation invocation) throws Throwable</span><br />
<span style="padding-left:20px;">{</span><br />
<span style="padding-left:40px;">Thread thread = new Thread()</span><br />
<span style="padding-left:40px;">{</span><br />
<span style="padding-left:60px;">public void run()</span><br />
<span style="padding-left:60px;">{</span><br />
<span style="padding-left:80px;">try</span><br />
<span style="padding-left:80px;">{</span><br />
<span style="padding-left:100px;">invocation.proceed();</span><br />
<span style="padding-left:80px;">} catch (Throwable e)</span><br />
<span style="padding-left:80px;">{</span><br />
<span style="padding-left:100px;">LOG.warn("Asynchronous method invocation failed.", e);</span><br />
<span style="padding-left:80px;">}</span><br />
<span style="padding-left:60px;">}</span><br />
<span style="padding-left:40px;">};</span><br />
<span> </span><br />
<span style="padding-left:40px;">thread.start();</span><br />
<span> </span><br />
<span style="padding-left:40px;">return null;</span><br />
<span style="padding-left:20px;">}</span><br />
}</code></p>
<p>So this inteceptor will make any method it intercepts asynchronous running the method on a separate thread and returning immediately.  So now I just needed to add the point cut to the spring application context.<br />
<code><br />
&lt;!-- Turns methods calls into asynchronous method calls --&gt;<br />
&lt;bean id="asynchronizeInterceptor"<br />
<span style="padding-left:30px;">class="com.scoreout.service.interceptor.AsynchronizeInterceptor"&gt;</span><br />
&lt;/bean&gt;<br />
<span> </span><br />
&lt;!-- Intercept caddie event recording method calls --&gt;<br />
&lt;bean id="asynchronizePointCut"<br />
<span style="padding-left:30px;">class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"&gt;</span><br />
<span style="padding-left:10px;">&lt;property name="advice"&gt;</span><br />
<span style="padding-left:40px;">&lt;ref local="asynchronizeInterceptor" /&gt;</span><br />
<span style="padding-left:10px;">&lt;/property&gt;</span><br />
<span style="padding-left:10px;">&lt;property name="patterns"&gt;</span><br />
<span style="padding-left:20px;">&lt;list&gt;</span><br />
<span style="padding-left:30px;">&lt;value&gt;com.scoreout.service.Audit.recordCourseRetrieval*&lt;/value&gt;</span><br />
<span style="padding-left:30px;">&lt;value&gt;com.scoreout.service.Audit.recordClientLogin*&lt;/value&gt;</span><br />
<span style="padding-left:20px;">&lt;/list&gt;</span><br />
<span style="padding-left:10px;">&lt;/property&gt;</span><br />
&lt;/bean&gt;</code></p>
<p>Now anytime I call com.scoreout.service.Audit.recordCourseRetrieval or com.scoreout.service.Audit.recordClientLogin the call will return immediately and the method will be run in the background.  For testing I can easily make these methods synchronous by either removing them from the application context or providing a new application context that does not include this pointcut (I generally prefer the latter).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2008/12/16/using-aop-to-make-calls-asynchronous-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>IE7 Tricks</title>
		<link>http://www.atwofer.com/2008/12/10/ie7-tricks/</link>
		<comments>http://www.atwofer.com/2008/12/10/ie7-tricks/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 18:09:51 +0000</pubDate>
		<dc:creator>Randy</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[IE7]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mootools]]></category>

		<guid isPermaLink="false">http://www.atwofer.com/?p=10</guid>
		<description><![CDATA[Hey, my first post and I already spent an hour setting up wordpress so I&#8217;ll keep it short.  Recently, we did an overhaul of our video management web application at Episodic.  Like any sane web developer I did all my testing in Firefox and then found myself with one day left before pushing to production [...]]]></description>
			<content:encoded><![CDATA[<p>Hey, my first post and I already spent an hour setting up wordpress so I&#8217;ll keep it short.  Recently, we did an overhaul of our video management web application at <a href="http://www.episodic.com">Episodic</a>.  Like any sane web developer I did all my testing in Firefox and then found myself with one day left before pushing to production and I had yet to look at our site in IE7 (IE6 not supported).</p>
<p>So I RDC&#8217;d to our one Windows box and, uh oh, it don&#8217;t look so good and there are a bunch of JS errors.  Here were a few of the main problems that I had to solve for IE.</p>
<p><strong>Trailing Commas</strong></p>
<p>IE does not like trailing commas in things like object declarations.  For example, you will get a very general JS error that points to a line that has nothing to do with the problem if you have the following:</p>
<p><code>var myObject = {<br />
<span style="padding-left: 10px;">foo: 'bar'</span>,<br />
<span style="padding-left: 10px;">baz: anotherObject<span style="color: #800000;">,</span></span><br />
};</code></p>
<p><strong>Positioning and Z-Index</strong></p>
<p>Our site has a lot of fancy drop-down menus.  The menu is absolutely positioned within some relatively positioned element and then given a z-index so that it appears overtop of other elements on the page.  However, this was a problem on IE when I noticed that my menu would actually appear behind some elements on the page.  In particular, the menu would appear behind other elements that have &#8220;position:relative&#8221;.</p>
<p>This took a while for me to figure out.  Eventually it came down to this: If an absolutely positioned element has a z-index then it&#8217;s containing relatively positioned element must specify a z-index (z-index:1) in order for the absolutely positioned element to be able to appear on top of other relatively positioned elements.</p>
<p>I did not come up with this on my own but it did take me a while to find this excellent page called &#8220;<a href="http://css-class.com/test/css/visformatting/layers/z-index.htm">Z-Indexing with position relative and absolute</a>&#8220;.</p>
<p><strong>Mootools Events Targets</strong></p>
<p>I LOVE <a href="http://www.mootools.net">Mootools</a>.  Eventually I will do another post about some Mootools tricks I have picked up but for now I&#8217;ll stay within the context of this post.  I have a lot of JS code that looks like the following:</p>
<p><code>someElement.addEvent('click', function(event) {<br />
<span style="padding-left:10px">if (event.target.get('tag') == 'li'</span><br />
<span style="padding-left:20px">event.target.dispose();</span><br />
});</code></p>
<p>However, the Mootools documentation says that <span style="text-decoration: underline;">the event target, is not extended with $ for performance reasons</span> (which actually only seems to be true in IE and would result in JS errors).  Therefore, the above case should be written as:</p>
<p><code>someElement.addEvent('click', function(event) {<br />
<span style="padding-left:10px">if ($(event.target).get('tag') == 'li'</span><br />
<span style="padding-left:20px">$(event.target).dispose();</span><br />
});</code></p>
<p>To avoid writing code like this everywhere I extended the Event class as follows:</p>
<p><code>Event.implement({<br />
<span style="padding-left:10px">getTarget: function() {</span><br />
<span style="padding-left:20px">if (!this.extendedTarget)</span><br />
<span style="padding-left:30px">this.extendedTarget = $(this.target);</span><br />
<span style="padding-left:20px">return this.extendedTarget;</span><br />
});</code></p>
<p>This left me with:</p>
<p><code>someElement.addEvent('click', function(event) {<br />
<span style="padding-left:10px">if (event.getTarget().get('tag') == 'li'</span><br />
<span style="padding-left:20px">event.getTarget().dispose();</span><br />
});</code></p>
]]></content:encoded>
			<wfw:commentRss>http://www.atwofer.com/2008/12/10/ie7-tricks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
