Posts Tagged ‘corgibytes’

Recipe: How to make your ruby version and gemset more visible when using rvm

Posted in Uncategorized on January 28th, 2011 by scott – Be the first to comment

I recently started using rvm for all of my projects. rvm is designed to help ruby developers work with multiple versions of ruby on their system. I recently came up with a great way always knowing with version of ruby is in use by rvm. But before I go into that, let’s talk about some details about rvm.

Installing a few rubys

Once you get rvm installed, you only need to run rvm install 1.9.2. That command will download and build the latest version of ruby 1.9.2 from source. If you also work with Phusion’s ruby enterprise edition, you can install it from source by running rvm install ree.

After running those two commands, you will have three versions of ruby installed on your computer, the system version, ruby 1.9.2 and ruby enterprise edition. However, if you run ruby --version you’ll notice that the system version is the one that is getting executed. Here’s what doing so looks like on my Mac running Mac OS X version 10.6.6.


cloudraker:~ mscottford$ ruby --version
ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]

However, if you first run rvm use 1.9.2, the running ruby --version should give you exactly what you expect. Try switching to ruby enterprise edition with rvm use ree. Again, running ruby --version should confirm that the switch took place correctly. Should you want to return to using your system’s version of ruby, just execute rvm use system.

If you ever need to check which version of rvm is active, you can run rvm current. This will output the name of the ruby that rvm has setup. We’ll discuss a better way to determine which ruby is active a little later. But first, let’s talk about how rvm helps us manage gems for each project.

Working with gemsets

Since just having different versions of ruby is not enough, rvm also gives us the ability to create different sets of gems that are completely isolated from each other. By default each version of ruby that we install gets its own gemset. We also have the ability to create named gemsets.

We create gemsets with the command rvm gemset create gemset_name. This will create a gemset for the currently selected version of ruby. One thing to keep in mind is that creating a gemset does not automatically switch you to that gemset. To do that you’ll need to use the rvm use command, for example rvm use 1.9.2@gemset_name. If you need to figure out which gemset is active, you can run the rvm currrent command. Once again, a better way to keep track of this is on it’s way.

Here’s a longer example that shows how to create and work with gemsets.


$ rvm use 1.8.6
$ rvm gemset create funkyness
'funkyness' gemset created (/Users/mscottford/.rvm/gems/ruby-1.8.6-p399@funkyness).
$ rvm current
ruby-1.8.6-p399
$ rvm use 1.8.6@funkyness
Using /Users/mscottford/.rvm/gems/ruby-1.8.6-p399 with gemset funkyness
$ rvm current
ruby-1.8.6-p399@funkyness
$ rvm use 1.8.6
Using /Users/mscottford/.rvm/gems/ruby-1.8.6-p399
$ rvm current
ruby-1.8.6-p399

Start using .rvmrc, and stop thinking

To make it impossible to forget which of your projects are using which versions of ruby and even then which gemsets, rvm will look for a .rvmrc in each directory that you switch into with the cd command.

Here’s an example.


$ rvm current
system
$ cd funkyness
$ rvm current
ruby-1.8.6-p399@funkyness

Okay. That looks like magic. What’s going on?

To answer that question, let’s take a peek inside of ~/funkyness/.rvmrc.


rvm 1.8.6@funkyness --create

With that one line, rvm will switch to ruby version 1.8.6 and gemset funkyness. It will even create it for you if it does not exist.

Since this feature could potentially be used to trick you into running malicious code on your system, rvm asks you to trust a .rvmrc file the first time that it reads it. You only have to do this once however.

What’s this post about again?

Now that I’ve explained the finer points about using rvm, I can finally start to vent a little.

I have several ruby projects that I’m working on at the moment. Some are for fun, but most are for my paying clients. I only recently started using .rvmrc files, and I’ve yet to create them for all of my projects. This means that for some projects, I don’t really need to think about which version of ruby is getting run, because it is the version that I’ve specified in the .rvmrc file. For other projects, however, I need to remember to run rvm use with the correct version of ruby for that project.

But I’d hate to run rvm use if I don’t need to. And running rvm current all them time seems a little silly. The solution that I’ve come up with is to alter the bash prompt to always let me know the current version of ruby that is in use by rvm.

To get started I used my favorite search engine to see if someone had already tackled this problem. I found one really good example that even introduced some color, however it was also using some git magic to include the current branch on the prompt. A few modifications later, I came up with my own version that just displays the ruby that is in use by rvm, and it does so while looking like it was copied and pasted out of Textmate.

Here’s what it looks like.


:rvm => 'system'
~ $ cd funkyness

:rvm => 'ruby-1.8.6@funkyness'
funkyness $ cd ..

:rvm => 'system'
~ $

CSS Unit Testing

Posted in Uncategorized on October 19th, 2010 by scott – 2 Comments

CSS is often not treated as code, but I’d like to make the argument that it should be treated as code. For instance, it needs to be easier to refactor CSS documents, and it needs to be possible to detect when there are CSS rules that are no longer needed.

I’ve read some recent discussions where the question of CSS unit testing has been raised. Many of these discussions devolved into a debate about whether or not CSS was “code”. A lot of these commentators complained about CSS not being a Turing complete language. I’d like to claim that this debate, with respect to unit testing, is a giant waste of time. Whether or not CSS is Turing complete has nothing to do with the reasons why one would like to write tests against CSS.

But to avoid that debate, I’ll avoid describing CSS as code. Instead I’d to propose that CSS is actually a domain specific language that is used to control the the way a browser works. For simplicity, let’s think of CSS as a configuration syntax.

CSS is a language that affects the way that HTML documents are displayed by web browsers. As the use of CSS has increased as the primary method for altering the way information is displayed, HTML documents have become more and more semantic. The additional tags that have been added to HTML 5 have made the documents even more semantic.

This means that HTML is basically just data that is displayed by a web browser. Web browsers have a default way of presenting this information. CSS is used to alter this default presentation, which means that CSS is simply a method for configuring the workings of a browser. Since CSS has an effect on the execution of a program, the web browser in this case, that is used for displaying information, it is important to ensure that the configuration is accurate for the task at hand.

This is where testing comes in. Testing should be employed any time that we want to ensure the correct operation of an application.

So can we stop the bitching and get started on a decent method for testing CSS already? I’ve got some ideas, but I’ll have to write about them later, once I’ve had a chance to work up some experiments.

7 Tips to Instantly Give Your Content Personality

Posted in ad copy, advertising, blog, blogging, branding, business, communication, conversation, copy, copywriting, corgibytes, creativity, customer service, marketing basics, small business, web copy, websites, word of mouth, work, writing on May 26th, 2010 by andrea – 5 Comments

Content with personality sells. Brands spend big bucks developing a distinct voice that makes them stand out. Conversational words engage your prospects instead of putting them to sleep, or worse, buying from someone else. This idea of copy that is personable and professional at the same time is what I built my career on. And here are some tips I’ve learned along the way to help your brand stand out from the pack.

1. Keep words and sentences short.
Big words do not make you sound smart. (I actually had to re-write that sentence. Originally it said, “Big words make you sound pretentious.” I have to keep even myself in check.) Long sentences make you seem boring. Readers, especially savvy web-oriented ones, don’t actually read — they scan. Short sentences keep these scanners more engaged, which leads to more sales. I try to keep most of my sentences to one thought, or clause. Sometimes two. More that that, and I try to break it up into separate sentences. Another way to put this idea is, “write like you talk.”

2. Use contractions.
When we’re talking casually, we use contractions — those “shortcut” words like can’t, won’t, shouldn’t, etc. We say – “I’d love to join you, but I can’t. Maybe next time, when I don’t have a conflict.”  In conversation, we’ll use the non-contracted form when we need to clarify or make a point. For example, “Joe, for the last time, I will not go on a date with you. Please, do not ask me again.” Using contractions instantly lightens the tone of your communications, and (you guessed it) makes your readers feel more engaged with your content.

3. Choose the “sparkle” word.
Which has more personality? “We’re happy to announce…” or “We’re thrilled to announce…” They essentially mean the same thing, but “thrilled” jumps out just a little more because it’s more exact. Happy is generic. It’s probably the first word you’ll reach for. Stretching just a little bit for that vibrant word can make your copy sing.

4. Write in the present tense, active voice, second person.
In non-academic terms, this means – avoid the words “have” or “been” and use the word “you”. Writing in this style is one of the most powerful ways to connect with your reader. It puts them in the here and now. It makes it feel like you’re having a conversation with them through the screen. Compare, for example, these two sentences: “We have enjoyed working with wonderful clients like you.” Versus, “You are a wonderful client. Thank you for your business. It makes ours more fun.” See the difference?

5. Know which (few) grammar rules you can break.
On occasion, I’ll start a sentence with “and”. I sometimes end with a preposition, too. That’s because these grammar rules help facilitate the conversational style. But there are some rules that when broken, make you look silly, or stupid, or ignorant. Here’s just a small sampling.

  • Your (you own it) vs. You’re (you are)
  • There (not here) vs. Their (it belongs to them) vs. They’re (they are)
  • Assure (give support) vs. Insure (to buy or sell insurance)
  • Affect (verb) vs. Effect (noun – can you put “the” in front of it?)
  • “A lot” is two words.

There are plenty more, and feel free to vent in the comments below. To keep your writing neat and tidy, try typing your opposing words in a search engine with “vs” between them. You can also check out The Grammar Girl.

6. Accessorize with styles.
Not to sound like your high-school English teacher, but rhetorical styles such as alliteration, metaphor, similes, rhyme, and repetition are marks of great writing. So use them. A word of caution though; too much of any of these styles, and you can easily swing to the other side of the personality pendulum (the one where you sound like an amateur and we don’t want that). It’s best to think of these styles like an accessory — add enough to accentuate your content, but not too much where you overwhelm the message.

7. Read out loud before you publish.
And by “out loud”, I don’t mean “really loud and slow but still in my head”. It means with your voice, at a natural volume. In addition to catching typos, this form of editing is perfect for making sure your content is conversational. Does it sound natural? If there’s a sentence that just doesn’t flow, work with it until it sounds right. Then, give your content to someone who hasn’t read it yet. Ask them to read it out loud. Then, massage any phrases that tripped them up.

With these simple tweaks, you can transform writing that’s bland and impersonal, into content that brings your readers closer to your brand. These are great tips for all sorts of business communications in both print and web. Have a question about how to implement these styles? Have a story about how you turned your copy around? Want to vent about your grammar pet peeves? Put it in the comment below.

Thanks, and happy writing!

Dynamic DNS with Rackspace Apps Control Panel

Posted in Uncategorized on May 24th, 2010 by scott – Be the first to comment

I use Rackspace Apps for email across all of my domains, and I am using them as a domain registrar, too. A few days ago, I wanted to create a subdomain, like example.vaderpi.com, that pointed to my computer at home. I didn’t want to use one of the free dynamic dns services, and I wanted to be able to create the subdomain for a domain that I already own.

Through the Rackspace Apps control panel, I can change all of the DNS entries for any of the domains that they are hosting. To create a subdomain, all I have to do is create an A record entry for “example” that points to my home ip address. I used whatismyip.org to look that up. Clicked “save”, and then the address started resolving right away. Perfect. Well, at least until my ISP hands out a different ip address.

What I needed was a programmatic way to detect that my ip address has changed and then update the A record entry for example.vaderpi.com with the new ip address.

I dug through the Rackspace Apps API documentation looking for a published way to do this, but I was unable to find one. Then I realized that I could just treat the control panel website as an API by driving it with a headless browser, like HtmlUnit.

There are several ruby gems that provide the ability to drive headless browsers. I took a quick look at celerity, mechanize, steam, and webdriver. I settled in on using steam, because it seemed like it had the fewest number of layers between it and the headless browser. I had also never used it before, and wanted to get a feel for how well it worked.

I have posted the resulting script as a github gist. Take a peek. Comments and forks are welcome. Note that all domain names, user names, and passwords have been replaced with made up examples.

As for running the script, I set up an @hourly entry in cron. The script only contacts the Rackspace Apps control panel if it detects an ip address change, so the risk of accidentally hammering their web server with this, should be low. (I point that out in case any of my old coworkers stumbles across this. :) )

The current implementation can only update an existing DNS entry, but it should not be too hard to extend it to support creating additional DNS entries. Anyone that goes to implement this should make sure to correctly handle clicking the add link if there are not any empty rows in the entry table.

In addition to supporting creating new entries, there are a few improvements that I would like to make to this script. (1) I’d like to have an external service resolve the domain. This is going to become critical, because I want my the domain to resolve to the private ip address for devices that are on the private network. (2) I’d like to not rely on whatismyip.org.

I’m thinking of writing a small web service that I can install on my server that will address both of these. The service will be able to do DNS resolution, and it will be able to detect the public ip address of the caller.

Rake recipes for working with Visual Studio projects

Posted in Uncategorized on February 3rd, 2010 by scott – Be the first to comment

Despite spending my day job coding in Microsoft-land, I find myself using ruby tools more and more during my daily development. I recently wrote some rake tasks that I think are worth sharing and explaining. Specifically, I wrote a tasks to control building with msbuild (seems redundant, I know) and some tasks for starting and stopping Cassini (or webdev.webserver as it is now named).

Monkey patch Pathname for Windows paths

Since I am using the Pathname class to build paths in my examples, I need to give you the monkey patch that I use to make Pathname correctly display win32 paths.


require 'pathname'
class Pathname
  alias_method :o riginal_to_s, :to_s
  def to_s
    original_to_s.gsub('/', '\')
  end
end

Visual Studio command line environment

Running command line Visual Studio tools requires having certain environment variables loaded. This can be done by running vsvars32.bat directly or by launching a Visual Studio command prompt from the start menu. This is something that I always forget to do; my terminal windows spring into life by typing cmd in the run box. So, I wanted to write a task to ensure that the environment was properly set up.

I am working with Visual Studio 2005. If you want to use the Visual Studio 2008 tools then you will need to adjust the vsvars32_bat variable accordingly.


vsvars32_bat = Pathname.new(
  "c:\program files\") +
  "microsoft visual studio 8" +
  "common7\tools\vsvars32.bat"
task :vsvars do
  if ENV["VSINSTALLDIR"].nil?
    `"#{vsvars32_bat}" && set`.each do |line|
      if line =~ /(w+)=(.+)/
        ENV[$1] = $2
      end
    end
  end
  raise "Eek!" if ENV["VSINSTALLDIR"].nil?
end

This code is the product of about 30 minutes of googling. I eventually found this trick in the shoes rakefile[1].

Now any task that needs to call a Visual Studio command line tool just needs to declare vsvars as a prerequisite, like so.


task :csc => [:vsvars] do
  sh "csc test.cs"
end

Building with msbuild

This is actually pretty easy once we have the environment set up correctly. Just create a task that calls msbuild from a sh call.


namespace :build do
  desc "Build the core project"
  task :core => [:vsvars] do
    sh "msbuild #{core_solution_path}"
  end
end

Controlling Cassini (or webdev.webserver)

There is a lot going on here, so let me first overwhelm you with the code, and then explain what it is doing.


def wait_until_site_loaded
  puts "Please be patient. Waiting for site to respond...."
  site_loaded = false
  until site_loaded
    site_loaded = system
      "curl -L -I -f http://localhost:2088/Default.aspx > NUL 2>&1"
  end
  puts "done."
end

namespace :web do
  desc "Start the local web server"
  task :start => [:vsvars] do
    Thread.new do
      sh "webdev.webserver /path:#{web_root_path} /port:2088 /vpath:/"
    end    

    wait_until_site_loaded
  end

  desc "Stop the local web server"
  task :stop => [:vsvars] do
    `taskkill /im webdev.webserver.exe > NUL 2>&1`
  end

  desc "Restart the local web server"
  task :restart => [:vsvars, :stop, :start]
end

Before the code block above will work, you will need to create a web_root_path variable that points to the absolute path of your website. Relative paths will not work.

The web:start task will start the web server. If an instance is already running at the specified port, then you will get an error message in the form of a dialog box. I wish I knew how to make it fail silently. (I also wish I knew how to prevent it from displaying an annoying balloon notification.)

After starting the web server, the web:start calls out to curl to make sure that the site is responding to get requests. I have curl installed as a result of installing cygwin. There are other ways to get curl, but you will need to make sure your path points at it’s location to use the code above without modifications. curl is pretty chatty, so I have silenced it by routing its standard out and standard error streams to NUL.

The web:stop task will kill all instances of Cassini. This might be annoying if you have more than one instance running. If that is the case, then you will need to write in some form of accounting for the process id of the web server process, or develop a way to figure out which process id owns the port you want. Once you know the specific pid, you can call taskkill /pid and pass it the pid of the process you want to kill.

The web:restart task will call web:stop task followed by web:start task.

One more thing: display available tasks from default task

Note: This recipe does not apply to just Windows development. It will work on any platform.

You can get a list of documented tasks by calling rake -T, but I always forget to do that. I usually just call rake when I want to know what it does. So I created a :default task that displays the same task list that you get when you call rake -T.


task :default do |task|
  puts "You must specifiy a task. Available tasks are listed below:"
  task.application.options.show_task_pattern = /.*/
  task.application.display_tasks_and_comments
end

That’s it. I hope you found these recipes helpful. Happy coding!

[1]: This is way off topic, so I stuck it in a footnote. I know it’s old news, but the way _why, the creator of shoes, committed Internet suicide really irritates me. There were a lot of people benefiting from his contributions to the ruby world, and then one day he just decides to take his toys and go home. He could have bowed out graciously, explaining that he had moved on, but he instead chose identity death. His works remain in archived form, but I am not sure if there is still any energy behind them.

10 Tips for a Kickass Wanted Ad

Posted in corgibytes, marketing on January 15th, 2010 by andrea – Be the first to comment

Here’s a great example of how to write a job description that works. I found this on Andy Sernovitz’s blog (a must have on your RSS feed if you ask me.)

Benifit-driven conversational copy gets you noticed.

10 Reasons why it works:

  1. The first word. You. Not me, I, we or any other form of the first person. You. It grabs the reader’s attention and makes your message relevant.
  2. Conversational tone. “Here’s the deal” is a great opening line. It closes the gap between the writer and reader. It makes your reader feel like they’re face-to-face, and opens an emotional bond. And in advertising, that’s a powerful thing.
  3. Clear benefits. Your reader wants to know, “What’s in it for me”. Give them clear and meaningful examples. Andy does a great job here with, “You will become a rock star with badass contacts. We will find you a job when you graduate.”
  4. Name dropping. Works every time. If you have the clout and the contacts, make it known.
  5. Edgy. Yes, this ad uses words like “shitwork” and “badass”. But it works here because of the audience. It makes your ad stand out amid a sea of corporate babble. Just make sure that you have the corporate culture to pull it off.
  6. Authentic. There’s no guessing that this job will require a lot of effort and work. In fact, they come out and say “You will be exhausted.” But transparency and honesty about the job (especially early in the process) just make you more credible.
  7. Keywords instead of tasks. “Blogging, Youtube, Social Media, Viral, Word of Mouth…” describe what the job is about without saying what the employee will be doing on a day-to-day basis. This helps ensure that qualified candidates won’t self-select out because they perceive they’re under qualified.
  8. Short & Simple. At just over 100 words, this ad packs punch. In just a glance and a quick scan, you clearly understand what Andy’s looking for and whether or not it’s a good fit for you. No need to drone on and on. We’re all too busy to read useless information.
  9. Written for the audience. This ad might not be the best fit if you were trying to find a more senior position, but for an intern, the edgy and conversational tone is perfect. This is how 19 year olds speak. Write how you (and your audience) speak.
  10. Clear call to action. “How to apply: blow my mind” (love this!) followed by three websites where you can learn more. Clear next steps are critical for increased response.

What are your thoughts? Is this an effective Wanted Ad? Or did it cross the line? Would you apply? Would you pass it on?

To your success,

Andrea :D

Watir Wait

Posted in Uncategorized on January 7th, 2010 by scott – Be the first to comment

I have been working with watir over the last couple of days. I quickly became frustrated with numerous errors claiming that the element I wanted to perform an operation on did not exist. I found the Watir::Waiter class and started using it extensively. So extensively, that I decided to write a little monkey patch to make my life easier.

The application that I am working with performs a lot of client-side DOM manipulation. This can create instances where my script was asking Watir to perform operations on DOM objects that didn’t exist. To defend against that, every time that I called click or set or select on various DOM objects, I wrote two additional statements. One to make sure the browser had finished whatever it was working on, and one to make sure that the element I was about to interact with actually existed.

The code looked something like this.


  @browser = Watir::Browser.new
  @browser.goto("http://localhost")

  @browser.wait
  Watir::Waiter.wait_until { @browser.text_field(:name, /UserName/).exists? }
  @browser.text_field(:name, /UserName/).set("Admin")

  @browser.wait
  Watir::Waiter.wait_until { @browser.text_field(:name, /Password/).exists? }
  @browser.text_field(:name, /Password/).set("Password")

  @browser.wait
  Watir::Waiter.wait_until { @browser.button(:name, /Submit/).exists? }
  @browser.button(:name, /Submit/).click

While that works, I got really sick of having to re-type the selector for the DOM element that I wanted to muck with. What I wanted to do was write code that looked something like this.


  @browser = Watir::Browser.new
  @browser.goto("http://localhost")

  @browser.text_field(:name, /UserName/).wait_to_set("Admin")
  @browser.text_field(:name, /Password/).wait_to_set("Password")
  @browser.button(:name, /Submit/).wait_to_click

Wow. That is much more concise and easier to understand. Even a non-programmer can understand what is happening now.

To make this code actually work, I decided to write a quick monkey patch that adds a “wait_to_” alternative for every method that can be called on input elements and links. These methods call @browser.wait, ask Watir::Waiter to wait for the element to exist, and then call the requested method.

I called my monkey patch Watir Wait. (Get it? I crack myself up! :) ) Take a peek and let me know what you think. If I get enough positive feedback, I’ll rework this into a proper patch and submit it to the Watir team for inclusion.

Database Dump: export the contents of your Oracle database

Posted in Uncategorized on December 18th, 2009 by scott – Be the first to comment

I created another small utility written in ruby. This one dumps the entire contents of a database to a text file. Contents are spewed to standard out, so you will have to pipe the output to a file if you want to do anything useful with it later.

Enjoy!

Ever wanted a database equivalent to grep?

Posted in Uncategorized on December 17th, 2009 by scott – Be the first to comment

I am always banging my head against the wall when working with legacy databases, because it is difficult tell where information is stored. Reading through the entire application code base to find the location of a string on the user interface is a very frustrating task. It would be much faster if I could just run grep '.*message.*'. I have been wishing that such a thing existed for quite a while, but I was unable to find one that did what I wanted. Start with a dash of ruby, add an hour of my time, throw in some tinkering, and bang. It’s done.

This version only works with Oracle databases, but it should not be too difficult to rework this to talk to database management system that you are mucking with.

Requirements: ruby 1.8.7 or later, ruby-oci8 version 2.0 (if on Windows, make sure you download the binary gem from rubyforge instead of trying to do gem install ruby-oci8)

Enjoy!

Instrumenting assemblies with Mono.Cecil and IronRuby

Posted in Uncategorized on December 16th, 2009 by scott – Be the first to comment

I just finished working on a script that I am really proud of. So proud that I want to share it with all of you.

I am working on making modifications to a third party application. I have source for some of the application, but unfortunately just having the source has not answered all of my questions. The application’s architecture is rather convoluted, and the source code is filled with hints that it was produced by very inexperienced hands. To steal a quote that I read on twitter a couple of months ago, “I was hoping to at least get spaghetti, but this code is just soup.”

So, I wanted to instrument the code so that I could get a better idea about what was going on in one particular library, specifically one that leverages Microsoft’s Workflow Foundation. My first stab at this was to just read the source in and add code to each method that marks the insert and exit points. I was planning on using the System.CodeDom libraries for this, and I was rather disappointed to discover that CodeParser is not implemented by the .NET Framework for C#.

So I turned to Mono.Cecil instead. I wrote a utility that modifies every constructor and every method. For each one, a message is inserted at the beginning of the method to note that it has started, and a message is inserted right before the return statement to note that the method is complete. Messages are transmitted through log4net, so you will need to play with your app.config to make the tracing messages show up.

The utility is written in ruby and will only run from IronRuby, because it makes heavy use of the .NET Framework. Oh, and the utility has the ability to apply and remove the instrumentation to an assembly, so you can put it back the way you found it.

Enjoy and let me know if you find any problems.