SmartLogic Logo (443) 451-3001

Blog

Using Sanitize Email to Preview HTML Emails Locally

April 30th, 2009 by

John Trupiano has a great post to get you started with sanitize_email for Ruby on Rails.

I wanted to preview my HTML emails without having to fill up my online email inboxes with tons of email (and then I’d have to make filters too). I also didn’t want to manage actually sending real email. So, I set up my machine for local delivery. Read on for instructions.
Read the rest of this entry »

environmentalist 0.2.3 released — supports rails 2.3.2

April 4th, 2009 by

Just a heads up that I’ve released environmentalist 0.2.3. You can update with:


  sudo gem install environmentalist

The only substantial change in this release is that we moved the loading of postboot.rb to the bottom of the boot.rb file as opposed to the top of config/environment.rb. This was necessary because common db rake tasks like db:create and db:drop stopped loading the environment in 2.3.2.

As a recap, environmentalist provides an executable that converts a rails app’s config structure. The basic idea is that environments themselves are now first-class citizens, allowing you to create several environments (e.g. staging, prodtest, demo, etc.) in a clean, organized fashion. Each environment is given its own folder where it can store its own set of configuration files (think mongrel configs, apache configs, etc.) without polluting the top-level config/ directory.

Slow Actions in Rails Projects

March 13th, 2009 by

MySQL’s slow query log is a very handy tool to detect which SQL queries are running slowly in a production app.

So what about rails applications? Often, test data only contains a small amount of data. Over time more users use the site and generate more data. A page that usually renders in 100ms could be taking 3-5 seconds, or more!

I present, SlowActions. The goal was to analyze a standard log file to detect actions that render slowly. It had to be easy to use and also not require modification of rails’ logging mechanism. Observe:

  $> slow-actions --actions development.log
             Cost    Average Max
  - UsersController : game_history (22 entries, 0% Error)
    Total:   11275.447 3642.437 12728.0
    Render:  7.20300 2.32700 17.2450
    DB:      10.5020 3.39200 10.0000

  - QuestionsController : refresh_index_table (89 entries, 0% Error)
    Total:   908.494 202.348 307.000
    Render:  0.00000 0.00000 0.00000
    DB:      32.5880 7.25800 10.0000

More info after the break ….
Read the rest of this entry »

Aptinstaller 0.3.2 Released

January 14th, 2009 by

Do you program ruby on rails? Do you use geminstaller? Do you run Ubuntu?

If you want to pull it all together, read on!

Read the rest of this entry »

Timecop: Freeze Time in Ruby for Better Testing

November 19th, 2008 by
The API mentioned in this blog post is specific to v0.1.0. The latest version is v0.2.0. See the blog post announcement, the documentation, or the github home page.

This past weekend I released v0.1.0 of the Timecop gem. Timecop makes it dead simple to travel through or freeze time for the sake of creating a predictable and ultimately testable scenario.

The gem is derived from a plugin I wrote a while back to achieve more or less the same functionality for an extremely time-sensitive application. My goals for the gem included:

  1. Drop-in-ability: The primary goal is to allow your app to continue to use Time.now, Date.today and DateTime.now as normal within your application. No overloading of functions with optional arguments (a la today=Date.today) just so you can write test cases.
  2. Environment independence: I wanted the gem to work (a) w/ rails (ActiveSupport actually), (b) w/ plain ruby when the ‘date’ library has been loaded, and (c) w/ plain ruby when the ‘date’ library had not been loaded.
  3. Library independence: I could have utilized mocha to achieve the mocking functionality found under the hood, but because I wanted this to work with plain vanilla ruby, libraries like mocha are out.
  4. Short-term time travel: I wanted to expose the ability to temporarily change the concept of “now.” This is particularly helpful when writing tests where time needs to pass.
  5. Long-range time travel: I wanted to expose the ability to change the concept of “now” for an indeterminate period of time. This is particularly helpful when setting up a rails test environment along with the test data.
  6. Nested time travel: I wanted to provide the ability to nest traveling, allowing the state to be kept within each block (we’ll see an example later).

The gem is hosted on RubyForge and can be installed by simply running:

sudo gem install timecop

Read the rest of this entry »

Watch Multiple Logs in a Single Terminal

November 12th, 2008 by

Have you ever opened 4 terminal windows, SSHed each one into a server, and ran tail on all of them to watch 4 log files?

Have you ever had a terminal window open whose sole purpose was to run “tail my_log” over and over again to look at the output of a file?

It’s a pain, isn’t it?

Introducing “Watch Me” a simple ruby script that allows you to watch multiple log files simultaneously.

go from this:

Before Watch Me

Using multiple terminals to watch logs

to this:

Using WatchMe to watch logs

Using WatchMe to watch logs

Read the rest of this entry »

Flex 3: Styling Individual Tabs in a TabBar

November 10th, 2008 by

There are a few ways to style the tabs in a TabBar that are fairly well hidden. Here are a couple methods that hopefully save some time for those of you out there looking to apply advanced styles tabs in Flex.

If you need to style the tabs uniformly, then you’ve got little work to do. Just set the StyleName attribute on the TabBar itself and just define it in your stylesheet.

<mx:TabBar id="tabBar" styleName="myTabBarStyle"  />
.myTabBarStyle {
	tabHeight: 28;
	cornerRadius: 0;
	horizontalGap: 0;
	horizontalAlign: right;
	backgroundAlpha: 1;
	backgroundColor: #357cc6;
	borderStyle: none;
	borderThickness: 0;
	dropShadowEnabled: false;
}

Now that’s all good and well when all your tabs look the same. What if you want to apply styles to tabs individually? Well, if you’ve got 3 tabs or less you can use some css selectors to reference the book ends specifically, and let the general style apply to the middle tab.

.myTabBarStyle{
    ...
  tabStyleName: "greenTab";
  firstTabStyleName: "blueTab";
  lastTabStyleName: "yellowTab";
}
.greenTab {
  fillColors: #a5d414, #87c408;
  backgroundColor: #87c408;
   borderColor: #87c408;
  themeColor: #a5d414;
}
.blueTab {
  fillColors: #5a9cd6, #357cc6;
  backgroundColor: #357cc6;
  borderColor: #357cc6;
  color: #ffffff;
  textRollOverColor: #ffffff;
  themeColor: #5a9cd6;
}
.yellowTab {
  fillColors: #333333, #333333;
  backgroundColor: #333333;
  borderColor: #646464;
  color: #F8ED6D;
  textRollOverColor: #F8ED6D;
  themeColor: #646464;
}

When you have 4 or more tags, you need to set their styles by getting a reference to the tab itself and call the setStyle() method. Straight forward? Yes. Easy to find information about? No… in fact I ran into trouble because there wasn’t any documentation available for an individual tab’s class and FlexBuilder 3 has no source code for the mx.controls.tabBarClasses package.

Import the Tab code, get a reference to the tab you wish to style, and call setStyle() for each attribute you want to change. Let’s say you have 4 tabs and each has a different style. You can combine all 3 methods of styling by using the css code above to set the tab style for all tabs in the tabBar, override styles for the first and last tabs, then specifically grab the 3rd tab and override its style in the component:

  <mx:Script>
    <![CDATA[
	import mx.controls.tabBarClasses.Tab
 
       private function tabBarCreationComplete():void{
	  var tab:Tab = tabBar.getChildAt(2) as Tab;			  
	  tab.setStyle("fillColors", ["#edb000", "#e69500"]);
          tab.setStyle("backgroundColor", "#e69500");
          tab.setStyle("borderColor", "#e69500");
          tab.setStyle("themeColor", "#edb000");
       }
    ]]>
  </mx:Script>

And update the TabBar control:

  <mx:TabBar id="tabBar" 
                     styleName="myTabBarStyle"
                     creationComplete="tabBarCreationComplete();"  />

You can iterate through each tab in the TabBar and set each tab individually if desired. I hope this helps some Flex developers out there who are confused by styling many tabs individually!

Making WillPaginate and Rails to_xml play nice with ActiveResource

October 10th, 2008 by

We are currently working on a project that involves Flex and active resource + will_paginate and we needed to be able to paginate the xml transactions easily. Unfortunately, will_paginate and to_xml don’t play nicely when it comes to adding the current_page, total_pages, and page attributes to the xml. After many failed attempts I went looking around github and found in a few forks of will paginate that some people had solved this problem but, I didn’t want to install another version of the gem to risk breaking other apps on the server so I did it the rails way!

I started by creating a module that opens up the will_paginate collection class and includes ActiveResource and alias method chain the to_xml method to include these values. Example code below.

#enviroment.rb
...
require 'to_xml_extensions'
#lib/to_xml_extensions.rb
module WillPaginateHelpers
  include ActiveSupport::CoreExtensions::Array::Conversions
  def to_xml_with_collection_type(options = {})
        serializeable_collection.to_xml_without_collection_type(options) do |xml|
          xml.tag!(:current_page, {:type => ActiveSupport::CoreExtensions::Hash::Conversions::XML_TYPE_NAMES[current_page.class.name]}, current_page)
          xml.tag!(:per_page, {:type => ActiveSupport::CoreExtensions::Hash::Conversions::XML_TYPE_NAMES[per_page.class.name]}, per_page)
          xml.tag!(:total_entries, {:type => ActiveSupport::CoreExtensions::Hash::Conversions::XML_TYPE_NAMES[total_entries.class.name]}, total_entries)
        end.sub(%{type="array"}, %{type="collection"})
      end
      alias_method_chain :to_xml, :collection_type
 
      def serializeable_collection #:nodoc:
        # Ugly hack because to_xml will not yield the XML Builder object when empty?
        empty? ? returning(self.clone) { |c| c.instance_eval {|i| def empty?; false; end } } : self
      end
end
 
WillPaginate::Collection.send(:include, WillPaginateHelpers)

This now gives me the proper xml when I call to_xml

<?xml version="1.0" encoding="UTF-8"?>
<time-cards type="collection">
  <current_page type="integer">1</current_page>
  <per_page type="integer">25</per_page>
  <total_entries type="integer">108</total_entries>
  <time_card>
    <approved type="boolean">false</approved>
    <billable type="boolean">false</billable>
    <created_at type="datetime">2008-10-10T14:04:13-04:00</created_at>
    <date type="datetime">2008-10-10T14:04:13-04:00</date>
    <has_been_billed type="boolean">false</has_been_billed>
    <has_been_paid type="boolean">true</has_been_paid>
    <hours type="float">2.0</hours>
    <id type="integer">98</id>
    <is_overtime type="boolean">false</is_overtime>
    <task_id type="integer">6</task_id>
    <updated_at type="datetime">2008-10-10T14:04:13-04:00</updated_at>
    <user_id type="integer">1</user_id>
  </time_card>
  ...
</timecards>

Benchmark Ruby Code with R, rsruby and better-benchmark

October 8th, 2008 by

I’ve found myself on a benchmarking kick these last couple of weeks. Sometime last week, I dug up the better-benchmark library written by Pistos. Pistos’ library is basically just a wrapper for the rsruby gem, which is more or less an interface to R (similar to what rmagick is to ImageMagick).

Combining these tools together, we can do some pretty nifty code performance analysis in very few lines of code, e.g.

require 'rubygems'
require 'better-benchmark'
 
result = Benchmark.compare_realtime(:iterations => 10) { |iteration|
  save_the_world()
}.with { |iteration|
  save_the_world_and_save_the_girl()
}
Benchmark.report_on result

I have forked better-benchmark and wrapped the library up into a RubyGem.

Read the rest of this entry »

Ruby: Patch to fix broken YAML.dump for multi-line strings (String#to_yaml)

September 4th, 2008 by

I love YAML. It’s portable. The majority of languages I work with already have libraries built to read/write it. It’s more lightweight, more expressive, and easier to read than XML. I really love YAML.

Unfortunately, it turns out that Ruby’s YAML library is a little incomplete for some edge cases. I just discovered that YAML.dump fails to generate valid YAML for certain multi-line strings. The specifics are very difficult to explain, and we’ll summarize them at the end after trying out some examples. Fire up irb and give the following a try.

require 'yaml'
s = "\n  Something embedded.\nAnd on a new line."
YAML.load(YAML.dump(s))

Read the rest of this entry »

  • You are currently browsing the archives for the Programming category.