Half-Penny For Your Thoughts

rounded down to the nearest cent



Categories


Recent Articles




Computing

Building a Builder, Part 3

This continues on two previous articles about setting up a custom FormBuilder for use in your Rails applications. See Part 1 (Introduction) and Part 2 (The helper method and related work on the NodeBuilder class). The particular Builder I’m working through is meant to generate simple tables and forms, nothing real fancy, with minimal view code. So, today, I’m going to look at creating a basic table via the builder.

In my last entry, I added the NodeBuilder#to_s method:

def to_s
  "<div>" + @rows.join("<br />") + "</div>"
end

I’m going to flesh this out to create a table instead of a div with line breaks:

def to_s

  # Setup table header
  headers = ""
  @headers.each { |h| headers << @template.content_tag("th", "#{h[:label]}") }

  headers = @template.content_tag("thead",
            @template.content_tag("tr", headers) )

  # Setup content rows of table
  content = ""
  @rows.each do |items|
    row_content = ""
    items.each { |item| row_content << @template.content_tag("td", item) }
    content << @template.content_tag("tr", row_content)
  end
  content = @template.content_tag("tbody", content)

  # Put header rows in content rows into table element
  return @template.content_tag("table", headers + content)
end

This takes information from the @headers and @rows variables and puts that data in a table, great for index views. The trickier part is getting that information into the variables. I’ll use the #field method to do that:

def field(label, content = "", options = {})

  # Allow just a symbol representing the attribute name to be passed. Use a titleized version of the field name for the label
  if label.kind_of?(Symbol) && content.empty?
    content = label
    label = label.to_s.titleize
  end

 # If this is the first item (row) populate the @header array; otherwise, it's already populated and can be skipped.
  if @item == 0
    @headers << {:label => label} # This is a hash because I might want to add more information later.
  end

  # If the content is a symbol, assume it's a method name on the current object.
  if content.kind_of?(Symbol)
    if content == :type # To avoid deprecation warnings
      content = @object[content]
    else
      content = @template.escape_once(@object.send(content))
    end
  end

  # Now, add the content to the @rows variable.
  @rows[@item] << content
end

Well, that’s pretty close to what I want, except that I want to also be able to use the with text_fields, password_fields, etc. So:

# create_labelled_field defines text_field and similar methods.
def self.create_labelled_field(method_name)
  define_method(method_name) do |label, *args|

    # if label is a symbol, assume its an attribute name;
    # use the titleized form of attribute name as the label.
    # In either case, call super without the label to get the content.
    if label.kind_of?(Symbol)
      args = [label] + args
      field(label.to_s.titleize, super(*args))
    else
      field(label, super(*args))
    end
  end
end

# This creates the methods for text_field, etc, which call create_labelled_field
(field_helpers + ["select"]).each do |name|
  create_labelled_field(name)
end

Yay. I may come back later and add some clearer explanations but this works (more or less) and provides a nice starting point to DRY-ing up forms. I may add a few more articles to this section, but they’ll probably be along the lines of “and here’s the goofy stuff you can do now…”


Computing

Social Networking in Short

I suppose the difference between a social networking environment and a community is simply the ability create and enforce a constitution.

That’s a nice thought, but it requires a mix of programmers and “community leaders” to enforce the constitution. Which would be no big deal in a web community for programmers.

Perhaps a domain-specific language for writing constitutions is in order.


Computing

Selenium with Rails

This past week, I’ve started using Selenium for integration testing of a Rails application. Writing the tests was pretty simple, thanks to the IDE, but setting them up to run using rake took me a bit. If you want the rake file, skip down a bit; first a few of the resources I found and comments thereon.

Okay, then, the post in “Steve’s Blog” got me to where I could run tests, but I finessed my Rake file a bit. My particular goal was to be able to run Selenium in a specific browser based on the rake task, and to have a task that runs several browsers.

namespace :selenium do

  desc 'Run Selenium java server'
  task :server do
    # dir would change based on where the selenium-server is located
    dir = "c:\\path\\to\\server"
    `java -jar "#{dir}selenium-server.jar"`
  end

  BROWSERS = %w{ie iexplore firefox safari opera}

  desc 'Run selenium tests in all major browsers'
  task :all do
    errors = %w(selenium:iexplore selenium:firefox selenium:safari selenium:opera).collect do |task|
      puts task.upcase
      begin
        Rake::Task[task].invoke
        nil
      rescue => e
        task
      end
    end.compact
    abort "Errors running #{errors.to_sentence}!" if errors.any?
  end

  # Create task for running tests in each browser
  BROWSERS.each do | browser |
    Rake::TestTask.new(browser.to_sym => "db:test:prepare") do |t|
      # t.options add the browser to ARGV to the test file.
      t.options = ["-- #{browser}"]
      t.libs << "test"
      t.pattern = 'spec/selenium/**/*_test.rb'
      t.verbose = true
    end
    Rake::Task["selenium:#{browser}"].comment =
      "Run selenium tests in #{browser}"
  end

end

In the test_helper.rb file, I added this to set a global $browser variable:

$browser = ARGV[0] || "iexplore"

$browser = "iexplore" if "ie" == $browser # because I'd rather just type "ie"

And, finally, in the test files:

# Server and URL settings may vary.
@selenium = Selenium::SeleneseInterpreter.new("localhost", 4444, "*#{$browser}", "http://localhost:4445", 10000);

Money

Worst. Invoices. Ever.

One of the companies I work for buys a lot of materials from CSC (in the interests of not getting in trouble, I won’t tell which CSC it is). As best I can tell their customer support is good, delivery time and materials available are fine, etc. In short, they do well with their central product. They’re not an accounting company, nor a print design group, so I don’t expect their invoices to be, well, great. But they fail to even manage “sucks utterly”. To the extent that if I was an owner instead of an employee, I’d refuse to order anything from CSC until they fix their bloody invoices. Well, probably not, but it sounds nice.

So what’s wrong with their invoices. Let’s start with the obvious. Five pages for 24 dollars. How that happens illustrates several of the other problems:

  1. Four lines per item. Now, this isn’t inherently bad. I’d be okay if they were four lines with a purpose. Alas, they’re a grouping of odd letters (more on item descriptions later). And they’re four big lines, so that there’s only room for about five items per page. These are not big-ticket items.
  2. Back-ordered items. All the items back-ordered on an order are listed on the invoice. This again is not necessarily bad, but for a combination of two reasons: the aforementioned amount of space taken by item descriptions, and that most of those back ordered items were shipped the same f—ing day.
  3. Massive header and footer space.
  4. They feel the need to use fixed-width fonts. Apparently, the invoice format was originally created for typewriters, and they’ve tried to stick as close to that as possible.

Now, then, jumping back to the description. They’re totally cryptic. Sometimes I can parse them. More often they feel like trying to read the comments on icanhas, except I don’t even have the vague hope of finding something funny. And, yet, they need four lines of text to tell me…nothing. I can’t begin to understand the reason for this. Yes, include a cryptic part number for your reference, but computers are quite capable of storing novels; readable descriptions are certainly within their grasp. And if they switched to a reasonable font, better descriptions need not eat up any more space.

Finally, what really annoys me, as I touched on earlier, is the sheer number of invoices. As best I can tell, CSC sends an invoice for every box shipped (They also send a packing slip with every box). It does not matter if they were all sent on the same day. So, combined with their listing of all back-ordered items, some days we’ve received five or more invoices, sometimes all for the same order, with the first listing every item on the order, even if it invoices the shipment of only a single item.

Anyway, just whining. No point, except to say that this would be an ideal situation for outsourcing. Let somebody else design the invoicing process, cos, CSC, what you’re doing…sucks.


Politics

Trust-Fund Tussle

I’m at Moe’s, eating my burrito, trying not to think of the stomach bug I’ve had the past four days. The news on the muted TV seemed an okay distraction (I wasn’t up to actual conversation). At some point, I looked up and saw in large letters “The Voice of Evil”. This was shortly followed by a photograph of Osama bin Laden. Given this photograph (and the Fox News logo), I’m assuming that the “Evil” entity referred to in the headline was bin Laden.

Mull that over a moment. Bin Laden. Capital-E Evil. I mean, yeah, the guy’s a selfish asshole, but “The Voice of Evil”. Do we really want to give to bin Laden the status of Sauron (or even the Mouth thereof), of Satan, of Voldemort, of, dare we suppose, Palpatine? Yes, I’m jesting a bit here, but all of these have a status–for at least some people–of being/representing evil incarnate (side note: think the “mythical” Satan here, the way he’s viewed culturally; otherwise, we could open a whole can of worms). So, what’s the problem with adding bin Laden to this group? All of these also have a particular psychological power, by virtue of being Evil. All, in their contexts, while powerful, suffer significant weaknesses, but these tend to be overlooked because of the way these entities are perceived.

By seeming bigger than life, the Evils have two major psychological powers:

1) The ability to draft others to fulfill their selfish plans. There may be a “cause” involved, but more significant is that other “bad people” draft off of the prevailing fears of this being.

2) Fear. Because this entity is Evil, I can conceive of he, she, it, or they doing anything to me. If I accept that conception, it inspires exceptionally strong fears.

We in the US have indeed granted Bin Laden a portion of both these qualities. That I would even consider the war in Iraq as more valuable to my personal safety than doing something about Interstate cell-phoners (and, I am admittedly an Interstate cell-phoner myself, although I try to keep it to a minimum) is irrational. But that irrationality is based on a fear of a repeat of the 9/11 attacks. Indeed, that this fear actually garnered support for the Iraq war is clear evidence of this irrational power (No, I still don’t know what they supposedly had to do with each other).

To make matters worse, that fear is continually placed specifically in the persona of Osama bin Laden. If I attribute to bin Laden the status of Evil, I resign myself to accepting his role in my life and culture, regardless of any real connection. As the war against Al-Qaeda has failed to materialize, the pundits have pushed the idea of bin Laden as a great Evil as an excuse for his continued real power; if we will instead acknowledge that the Bush administration in particular (and many others in general) mismanaged their post-9/11 offensive, bin Laden loses power. We could instead focus on an improved scheme for eliminating both the current offensive abilities of terrorist groups and the social, economic and political issues that make these groups attractive to a given population.

So let’s consider what bin Laden is if he is not Sauron. Bin Laden is a trust-fund kid. I don’t know much about his personal life, but it wouldn’t surprise me if he got interested in politics and religion out of a combination of boredom and wanting to prove himself. Pride, idleness and available resources is a most dangerous combination (by the way, it rather concerns me that the primary disciplinary action in modern Western culture is forcing idleness on people who have just had their pride hurt).

The current war on terror can then be seen as a pissing match between two trust fund kids. In that light, a second definition of Evil appears. This is the type of Evil that the rivalry football team is. “The Fighting Carrots are evil”, might say a member of the school on the other side of the state. Most times this is in jest, but an insult placed wrongly can turn it ugly. If such a rivalry definition of evil can be turned for political gain, it will be. Consider the Cold War. Certainly the USSR’s government did some evil things, but the “communism is evil” has a lot of the rivalry sense; indeed it’s hard for me to interpret “the space race” in any other light. Folks like McCarthy saw the political potential and acted to turn communism from a rivalry evil (if only in part) to an Evil.

There is a natural conclusion to this: Vietnam. To generalize, creating an Evil for political (or “news entertainment”) ends generates conflicts with no reasonable particular purpose or well-defined goal. People lose their lives fighting an Evil that is at worst no more than a rivalry, at best a sociopath with lots of guns who could be better dealt with if we acknowledge what that entity really is.

I don’t know if I could, but I’d like to say I’d be willing to sacrifice my life to end Al Qaeda’s ability to kill people (note that I don’t know how to go about that, which is partly because even writing this article I struggle to mentally separate that goal from Iraq). I’d even like to say I could sacrifice my life for the creating a more secure environment for Iraqi children, although I’m confident I have no idea how to that (dividing Iraq into multiple independent states might be a decent start though). But I am not in the least willing to lose my life fighting a mythical Evil that has some theoretical connection to Iraq. And that is so hard, to see a list of those who have died who, yes, fought very real problems, but who, from the perspective of the Bush administration and much of congress where ultimately fighting an Evil that is a product of press releases.


Epilogue: This point isn’t central to my above article, but I think it bears mentioning, if only because it might clarify some of the above thoughts. It’s early year in the 2008 election season (not that you’d know it was still early from the five-nightly debates), but I have done some thinking about the candidates. Up until tonight, preparing to write this article, I hadn’t seen any reason for caring that Clinton is a woman. Sure, if all else was equal, I might vote for her above a man just because I enjoy seeing stupid traditions fail, but I can’t see where her being female would affect her governing decisions in significantly different way than the male candidates.

Tonight, though, I see one possible arena. I’m a guy, and I know a lot of guys, and I know that rivalries are something we guys tend to get into. Blowing those silly rivalries way out of proportion is something we also seem to enjoy. That any male president could think of bin Laden as a rival, could transfer that rivalry onto Hussein in order to get on “more comfortable turf” is not so surprising, because rivalries are an element of the (a?) cultural “man” role in the US.

I would like to think that a woman president might have been more likely to take the 9/11 attacks as an attack on a family (in this case, the US population in general) rather than as a point in a “my dick is bigger” match. If this is accurate–and it may not be–it may help explain something that has been bothering me about Clinton. Overall, I feel she would be an excellent president, except for what has seemed to me to be excessive support of the administration’s (flawed, in my opinion) response to 9/11. However, I may need to rethink this, because I suppose I have been assuming that her response is based on a rivalry philosophy. If not, her execution of that response, as the Executive, may be entirely different.