One would think it would be quite easy to graph the simple economic functions of supply and demand using something like OpenOffice or Gnumeric. Alas, this is not the case at all. The major dilemma is that, with economic functions of this sort, the dependent variable is represented on the X axis, as opposed to the Y-axis (think y = mx + b).
After searching extensively under the Line Chart components for OpenOffice and Gnumeric, I failed to find a “switch dependent axis,” or some such.
I finally discovered that the best way to accomplish the task is via an “XY plot” in Gnumeric. I have attached a file to this posting, which should allow you to determine how to make your own economics graphing data work.
I hope this information helps someone.
After a good many hours looking at what I can only deem an asinine attempt at Perl coding, I have rewritten the hook script meant to interface a Subversion repository with FogBugz. Hopefully this Ruby will save some others the pain I have endured this day.
#!/usr/bin/ruby
class String
def to_url
gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase
end.tr(' ', '+')
end
end
repo_path, transaction = ARGV
svnlook="/usr/bin/svnlook"
logmsg = `#{svnlook} log -r#{transaction} "#{repo_path}"`
changelog = `#{svnlook} changed -r#{transaction} "#{repo_path}"`
changed_files = changelog.split(/\n/)
changed_files.collect! do |cf|
ary = []
cf.scan(/^(\w)\s+(.*?)$/) { |type, path|
if type == "A"
ary = [0, path]
else
ary = [transaction.to_i - 1, path]
end
}
ary
end
logmsg.scan(/(?:#|case )(\d+)/).each do |bugid|
changed_files.each do |previous_transaction, path|
unless previous_transaction == nil || path == nil
`wget -q -O /dev/null "http://localhost/fogbugz/cvsSubmit.php?ixBug=#{bugid}&sFile=#{path.to_url}&sPrev=#{previous_transaction}&sNew=#{transaction}"`
end
end
end
The more I am working with rSpec view specs, the more I am thinking that the quantity of code used to define certain behaviors can be significantly reduced. I have been trying to combat duplication, like a good, DRY programmer, but this approach has led to cumbersomely named methods (e.g., specify_should_render_select_list_for) and a convoluted spec_helper.rb (weighing in at around 250 lines so far).
My latest machinations on the subject are aimed at creating new conventions, or perhaps leveraging existing Rails conventions. For example, say I need a select box rendered to choose the bar_id for the belongs_to :bar association of my foo object. In my view I would have code like the following:
<%= collection_select 'foo', 'bar_id', @bars, :id, :name %>
It seems reasonable to be able to specify the spec in a similar, minimalistic fashion, such as:
validates_collection_select :bar_id
This single statement would generate specs to test the cardinality of the select list, the uniqueness of each of its elements, and so forth.
I will be experimenting with this code reduction further and, with any luck, will actually come up with some code that may benefit the rSpec project.
I have finally implemented a new version of my example program: Dictoquiz. I have tried to implement some of the suggestions from Professor Jernstedt, and have modified the workflow considerably. Now, instead of the computer evaluating a literal definition, I have the user rate her/his response accuracy. Enforcing literal definition memorization was definitely a poor idea.
Cruise over to dictoquiz.chrishoffman.net to get an overview of the program, and to pick up the source.
So, I have a bunch of very similar keys in a hash (e.g., question_1, question_2) that I want to get at once. I could run the whole hash through a collect block with an if statement to prune out the keys of interest, but where is the fun in that? I went in search of a more idiomatic way of accomplishing what I need.
Observe:
class Hash
alias :old_index :[]
def [](search_term)
if search_term.kind_of?(Regexp)
self.collect { |key,val| val if key =~ search_term }
else
old_index(search_term)
end
end
end
In order to retrieve all of the keys starting with question_, for example, I need only do the following:
questions = {
:question_1 => 1,
:question_2 => 2,
:not_a_question => false,
:question_3 => 3
}
questions[/question_\d+/] #=> [1,2,3]
I love Ruby!
The performance hit one takes for using the after_find and after_initialize callbacks has been well documented. However, what if one needs to implement per-instance functionality?
For example, say you have class Foo that has_many bars. If Foo has the fewer_bars attribute set, then there should be a limit added to the options of the has_many method. The after_find approach may look like the following:
def after_find
f = class<<self; self; end
if fewer_bars
f.has_many :bars, :limit => 10
else
f.has_many
end
end
Now this method gets loaded up each and every time an instance of Foo is created. If we only access bars occasionally, this is a huge performance hit. Instead, consider the following code:
def bars
super
rescue NoMethodError # has_many hasn't yet been called
f = class<<self; self; end
if fewer_bars
f.has_many :bars, :limit => 10
else
f.has_many
end
bars
end
The first time this method gets called for an instance, the has_many association gets set up. The only part that tripped me up about this implementation was that calling super instead of bars, at the end of the rescue clause, throws another NoMethodError. I surmise that bars still not being defined without reintering this method (via the bars) is due to some scoping issue. I really am not motivated enough (or smart enough) to investigate further.
Mainly to keep some record of the knowledge I accumlate while using Rails, I am going to start jotting down some things I consider to be best practices.
Tip #1: Mixin Presentation-Modifying Functionality
I have a view that loops through a data structure, printing it out in tabular format. All this loop cares about is that to_s is implemented. I want a particular field of the object to be printed, instead of the usual #<SomeObject:0xb6485858> object dereference. The field to be printed depends on the sort of object currently being iterated upon. So, at one point of the loop it might be a FooObject, in which I want to print the #foo attribute, and later it might be a BarObject, where I want the #bar attribute printed. That is, simply calling object.field from the view won’t work.
To remedy this situation, one might think to override #to_s in the model itself, which indeed would work for this particular situation (and was how our team addressed this scenario in the past). However, what happens when you need #to_s to work differently in different contexts, printing #foo in one view, and #qux in another? One approach might be to add a conditional in the view on object type, printing the field explicitly (i.e., not overriding #to_s at all), but this is much too procedural.
Enter the Mixin
Instead, consider extending the particular objects that each view accesses. Where better to put this functionality, than in the place where data is prepared for the view’s use: the controller.
foo_obj = Foo.find(:first)
def foo_obj.to_s
self.foo
end
Though I’ve had the source to my DictoQuiz hosted for some time at src.chrishoffman.net, I have wanted to integrate some nice syntax highlighting, so that people who don’t normally work with Ruby can get a better sense of what the code means.
I started by looking for a lexer, and came across another gem (pun not intended) by Jamis Buck; this guy is amazing, he is a coding machine. Anyway, it was really easily set up via gem install syntax. After figuring out how to get this gem loaded into a script, by following the example at Wolfmans Howlings’ blog, I realized that I didn’t really have a way of getting this script executed yet. I really didn’t want to make a whole new rails app for a single script, so I investigated some way to put some cgi into the lexer, and serve it up.
To add cgi goodness, I searched and came up with the perfect section from the first edition of the pickaxe book.
The final piece of the puzzle, then, was to rewrite URLs such as src.chrishoffman.net/db/schema.rb to src.chrishoffman.net/print_syntax.rb?file=db/schema.rb. I accomplished this with the following configuration:
$HTTP["host"] =~ "^src.chrishoffman.net$" {
server.document-root = "/home/hoffmanc/dictoquiz"
server.dir-listing = "enable"
dir-listing.hide-dotfiles = "enable"
cgi.assign = (".rb" => "/usr/bin/ruby")
url.rewrite-once = ( "/(.*\.(?:rb|yml))$" => "/print_syntax.rb?file=$1" )
}
I was afraid of an infinite loop if you actually try to load /print_syntax.rb itself, but it seems to work alright; it’s a little twisted that the script processes itself ;)
Now the only thing left is to make this script execute via a fastcgi process, as cgi processes are notoriously slow.
A jazz band of which I’m a member, has just cut a couple of demo tracks, to help us get some gigs in the future. Check them out:
Boot the Cat
Members
- piano – Mark Brisson
- vocals – Chloe Brisson
- bass – Chris Soderquist
- tenor – Chris Hoffman
Tracks
$HTTP["host"] =~ "^(www.)?chrishoffman.net$" {
server.document-root = "/host-wide/document/root"
$HTTP["url"] =~ "^/blog" {
server.document-root = "/url-only/document/root"
}
}
lighty fails to change the document root for requests under /blog, but does so silently. It would’ve been glorious to receive a parse error, instead of having to track it down, via a comment out line, reboot server, load page cycle.
The way I’m getting around the bug is by redirecting to different subdomains, like so:
$HTTP["host"] =~ "^(www.)?chrishoffman.net$" {
url.redirect = (
"^/(?!downloads|trac)$" => "http://blog.chrishoffman.net",
"^/trac$" => "http://trac.chrishoffman.net"
)
}
Then I do the server.document_root declarations within additional $HTTP["host"] variables, which seems to work. It’s a bit of a kludge, but still way better than Apache.