Finally Improving My jQuery

Taking a break from rails tonight to go through the peepcode video on jQuery. The advice I had from a pal is that jQuery is easy and separate enough from javascript that it can be learned by itself. I’m not certain I agree just right now, but it’s definitely a big eye-opener.

The big take home point for beginners here seems to be learn the following:

$()

is a wrapper function. It serves mainly to take an argument, and make a jquery methods available on that argument. For example:

$("#someId")

will wrap the someId element on a page inside jQuery and make jQuery methods available:

$("#someId").fadeOut

The other thing is that you’re going to be doing a lot of finding elements, so learn your bloody selectors! The jQuery documentation on selectors contains a bunch of jQuery specific stuff. Otherwise, I’ve been mostly learning them via writing selenium automation tests at work. 

I have a ton of documentation to research on test the rails view for a talk I’m leading tomorrow. Wish me luck!

 

 

Finally Improving my Rails

I’ve known bits and bobs about rails for years, but I’ve never sat down and tried to force myself to be a front-to-back rails developer. It seems weird to say that, because I’ve actively loved the ruby language for years and rails has been something I’ve made a living from supporting before, but my jobs have pulled in non-rails directions (windows, perl, learning vmware, networking, linux systems administration, more perl, more vmware, then lots of security and networking). Combine that with a wonderful relationship, lots of independent interests and it’s been hard to get time together to sit down and focus on rails by itself.

I’m newly single, though, and slimming down my interests a little and I’ve got time to be pursuing some stuff I’ve had on the back burner for a long time. The first of these is forcing myself into learning rails more thoroughly, from soup to nuts.

I’ve had a few ideas for a trouble ticket application to help at work, so I decided to start by making a simple rails app that will track tickets. Each ticket is an idea I’ve had for improving the app itself, so it’s useful from day one and immediate utility tends to keep the interest.

My immediate problem stems from having written a simple test:

test "Only high priority items are returned." do
tickets = high_priority_tickets
tickets.each do |ticket|
assert(ticket.priority =~ /^high$/)
end
end

I’m making the assumption here that I can write some method high_priority_tickets which will return all tickets with a priority of high. I don’t know where to put it, though!

I’m making the bet that it goes in the model for two reasons:

  • the model provides data for the controller/view
  • unit tests in rails are designed to test the model, integration tests are designed for the controller (c.f. http://guides.rubyonrails.org/testing.html)

Still, it’s these kinds of small decisions I’ve not had to make before. It’s exciting getting to see my own rough edges.

Proc and Lambda and Block (oh my)

Something neat about  ruby is the equivalence of procs, lambdas and blocks. Take a quick look here:

foo = Proc.new do |x|
puts "In a proc. X is valued at #{x}"
end
foo.call(24)
output -- "In a proc. X is valued at 24"

Pretty simple. Much like an UnboundMethod object, you have to call the proc with call. It can have variables supplied to it with the slide operator ||, or it can inherit the same from the surrounding scope:

x = 1
foo = Proc.new do
puts "In a proc. X is valued at #{x}"
x = 25
end
puts "#{x}"
-- outputs 25

A lambda is an alternative proc syntax. Instead of explicitly creating a proc object, you get an anonymous one still bound to a variable:

bar = lambda { |x| puts "In a lambda. X is valued at #{x}"}
bar.call(32)
--- output "In a lambda. X is valued at 32"

Now, let’s take a look at a block. First, we define a method that yields to a block:

def runnable
puts "Inside runnable."
yield
puts "Still inside runnable."
end

 

Now, we call the method with the same “do” keyword we already used for the proc:

runnable do
puts "I am a block."
end
--output: Inside runnable.
I am a block.
Still inside runnable.

Much as you can insert Proc.call anywhere inside a scope, so you can also insert yield inside a scope and define the proc on-the-fly in a block. Compare the syntax of yielding a variable to that of using a variable with a Proc:

def runnable
puts "Inside runnable."
yield(42)
puts "Still inside runnable."
end
runnable do |x|
puts "#{x}"
end
output -- 42

This allows an associated block to use a variable set within the method. What’s neat, though, is that we can see that the method that yields has a key difference to a Proc: it cannot see into the external scope:

x = 1
def runnable
puts "Inside runnable."
yield(x)
puts "Still inside runnable."
end
runnable do
puts "I am a block."
end
--output - this code fails with an error.

There’s a scope defined by the method, and the variable x is different inside that method than outside of it. 

All this is documented in a github repo: https://github.com/jamandbees/proclambda — feel free to look through the history and goof around.

conway update

I got half way into Conway and haven’t picked it back up yet. 

The first problem conceptually as that I was stuck thinking about coordinates and coordinates and how does a cell know it has a neighbour and coordinates and neighbours?!

The solution came to me while I was on the bus, going down a beautiful canyon. The cell is a class. It cares about how many neighbours it has, so that it knows whether it is alive, dead or unchanged. 

The world tracks the position of the cells. The information the cell needs is how many neighbours it has. Not its own position, not how big the world is.

I need to write  a world for my cells to live in. Then I’d like something to output graphical information to. I think an ncurses UI would be fine first.

I should upload this to github or something.

 

 

Ideas Ideas Ideas.

Well, daily coding failed as a project. I don’t know whether it’s a discipline issue, or an interest issue, but trying to come up with artificial ways to keep progressing skill can be hard.

 

I’m updating my freebsd vm. I like keeping it around as a standard platform for writing ruby and for testing my code on. If it works on mac os, deploy to FreeBSD and verify it still works. If it does, yay! Whilst doing this, I’ve been trying to come up with a program-y project.

I have a couple of ideas that I’m batting around. Log parsing, message passing over a socket, having worker drones which report back to a central reporting facility. Solved problems, sure, but ones I’m interested in solving myself. Thinking about old problems that I want to re-solve, it hit me that I can write Conway’s game of life.

The rule set isn’t hard to implement, but I’d like to have a UI element too. This means either implementing a command line output with ncurses or whatever, or bringing up a window and drawing to it. Both of which seem very cool. I may even try both.

This seems like a good idea somehow.

New Project — Daily Coding

I heard today about a guy who committed to commit some finished piece of his own code to a project every day for a year.

I thought it sounded good. So I decided to start with some project euler.

https://github.com/jamandbees/project_euler

Hopefully, the various rails projects I have in mind will eventually be part of this, but I wanted to start somewhere small.

Fewer, More Flexible, Options

I had a weird situation at work today. I have a script which runs for a specific amount of time:

script.rb --time 360

I had to add an option to make it run, then sleep, then run, then sleep, and so on. But I also still had to support the total time option.

The first thing I did was come up with a working model inside the code to support “run, then sleep, then run, then sleep”. I decided on a multidimensional array:

timeArray = [[100, 200], [150,300], [10,30]]

And I iterated over each:

timeArray.each do |timeArray|
timeToRun = timeArray[0]
timeToSleep = timeArray[1]
end

Now that was out of the way, I came up with comma-separated-semicolon-delimited strings as a way of specifying this on the command line:

script.rb --runandsleep 100,200;150,300;10,30

I called split on a semicolon first to give me a bunch of arrays containing each comma delimited string, then split on the comma and cast to integers using .to_i:

timesToRun = runAndSleepArgument.split(";")
timesToRun.each do |runAndSleepString|
sleepAndRunTimes = runAndSleepString.split(",")
runTime = sleepAndRunString[0].to_i
sleepTime = sleepAndRunString[1].to_i

All’s well and good, but what if the combination of run and sleep are specified with the total run time?

script.rb --time 150 --runandsleep "30,30;60,60;90,90"

I flopped back and forth for a while. I could preparse the –runandsleep time and if it was greater than the –time then refuse to run. That’d solve it. I could just run for the greater of the two times.

But what if someone enters:

script.rb --time 10000 --runandsleep "30,30"

I could run for 30, sleep for 30, then run for 9940. That had a decent solution.

The problem in my mind here is that I know what these kinds of things are like. I added a command line flag to this script (which is used a lot) called –destroy, because it called the destroyAllHumans function which reset a database. Within a week, the developers and QA were talking about how they were running with DESTROY or not with DESTROY and how it impacted things. As such, I know that the flags enter peoples’ heads. They get inside.

If the flag is non-intuitive, the person using the script is irritated. If the flag is intuitive, the person using the script thinks in terms of the flag.

So I solved the problem thus. You can specify:

script.rb --time 300

or you can specify:

script.rb --time "100,50;100,30;10,100"

Both of the syntaxes really specify a total run time, so why make them different? The script becomes better because it has fewer, more flexible, options.

Ruby 1.9.3 on Mac OS X Lion with XCode 4.3

I wanted to install rails 3.2.4 on Mac OS 10.7. The system ruby is 1.8, but I wanted to run against 1.9.3, and it was tricky getting everything working with XCode 4.3.

I wanted to use RVM, but right now RVM spits out an error telling you that 1.9.3 is kind of covered with XCode 4.3, that prior versions of ruby aren’t supported with 4.3, and that you might want to install OSX-GCC-Installer and remove XCode. If you want to go down that path, the OSX-GCC dude seems like a nice bloke: http://kennethreitz.com/xcode-gcc-and-homebrew.html

I didn’t! As such, I decided to see if homebrew would install ruby 1.9.3 (it does) and how hard it would be to switch between its version of ruby and the system ruby (it’s trivial).

  • Remove rvm if you’ve installed it:
    rm -Rf ~/.rvm
  • Install XCode 4.3 from the app store.
    Once installed, open XCode -> Preferences -> Downloads -> Command Line Tools. Download ’em.
  • Install HomeBrew: http://mxcl.github.com/homebrew/. Do your best with their post-install instructions. I especially found it useful to uninstall macports http://guide.macports.org/chunked/installing.macports.uninstalling.html
  • Install ruby 1.9.3: brew install ruby
  • Open .profile (or .bashrc or whatever bash config file you’re using) and add
    PREPATH=$PATH
    #homebrew suggests putting usr/local/bin before /usr/bin
    export PATH=/usr/local/bin:$HOME/.gems/bin:$PATH
    alias unbrew="export PATH=${PREPATH}"
    

    Now, if you want to use the system ruby you run unbrew from the command line

Sockets, Arbitrary Ruby and C

I’ve had this small project in mind to write a server which would execute arbitrary ruby. I didn’t want to have a concept of state, so assignment and memory management weren’t a big deal.  It should:

1. Accept a class method, like puts “Hello, world!”
2. Output on the server “Hello, world!”
3. Output on the client “puts “Hello, world!””

I knew GServer existed in the stdlib, but didn’t know how to work it. I saw a neat trick on the peepcode  screencast with Aaron Patterson: download the source tree and ask _that_ your questions, don’t bother with the docs.

I downloaded ruby’s source tree, kind of nervous, and found the GServer implementation using sublime text’s fuzzy search function. The comments said to just inherit from the class and implement the serve method, and all would rock.

I was surprised by how much cleared reading the source and comments were than reading the rdoc that’s generated from those same source and comments. I was reading through the code really happily, learning about GServer, and managed to get the functionality I was looking for in about 20 minutes. If you want to download the code, it’s available on github: https://github.com/jamandbees/arbitrary-server

One of the neat things reading the code was that I actually read the implementation of each method, and I noticed something in the start method that got me thinking. There’s a class to create a new TCPServer:

 @tcpServer = TCPServer.new(@host,@port) — from GServer.rb

The requires for the class are socket and thread, so I assumed this came from socket. I read socket.rb, though, and I honestly didn’t see a TCPServer definition, so I checked its requires: socket.so.

Socket.so is a compiled library. I did a quick search for socket.c and found documentation in there that references TCPServer.new, but which doesn’t seem to have any implementation that would recognise the name “TCPServer.new”.

Socket.c includes rubyserver.h. Reading that, I saw these two lines:

extern VALUE rb_cTCPServer;

void rsock_init_tcpserver(void);

So we’re mentioning a tcpserver in an included library, finally!

From here, I didn’t know where to go.I did a search of the source tree for tcpserver and found tcpserver.c. It also includes rubyserver.h, so presumably somewhere in that include is where the relationship between socket and tcpserver is created, but I can’t see where.

I do see where the class is made, though:

void
rsock_init_tcpserver(void)
{
  /*
  * Document-class: TCPServer < TCPSocket
  *
  * TCPServer represents a TCP/IP server socket.
  *
  * A simple TCP server may look like:
  *
  * require 'socket'
  *
  * server = TCPServer.new 2000 # Server bind to port 2000
  * loop do
  * client = server.accept # Wait for a client to connect
  * client.puts "Hello !"
  * client.puts "Time is #{Time.now}"
  * client.close
  * end
  *
  * A more usable server (serving multiple clients):
  *
  * require 'socket'
  *
  * server = TCPServer.new 2000
  * loop do
  * Thread.start(server.accept) do |client|
  * client.puts "Hello !"
  * client.puts "Time is #{Time.now}"
  * client.close
  * end
  * end
  *
  */
  rb_cTCPServer = rb_define_class("TCPServer", rb_cTCPSocket);
  rb_define_method(rb_cTCPServer, "accept", tcp_accept, 0);
  rb_define_method(rb_cTCPServer, "accept_nonblock", tcp_accept_nonblock, 0);
  rb_define_method(rb_cTCPServer, "sysaccept", tcp_sysaccept, 0);
  rb_define_method(rb_cTCPServer, "initialize", tcp_svr_init, -1);
  rb_define_method(rb_cTCPServer, "listen", rsock_sock_listen, 1); /* in socket.c */
}

So, as long as I can get from tcpserver.c through to socket.c, I think I’ll be okay.
Funny how you sometimes wander down paths.

no main manifest attribute in maven jar

Maven have a pretty awesome tutorial in their getting started guide here: http://maven.apache.org/guides/getting-started/index.html

The problem is that if you follow it letter for letter, then run:

java -jar target/<jarname.jar>

you receive a “no main manifest attribute” error.

Stackoverflow has a good answer for this problem, but it took a few readings before I understood what they were saying. Here’s a link to the stackoverflow question:

http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven

Open your pom.xml and add the section listed:

<build>
   <plugins>
      <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
          <archive>
               <manifest>
                    <mainClass>fully.qualified.MainClass</mainClass>
               </manifest>
          </archive>
     <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
 </configuration>
</plugin>
</plugins>
</build>

This goes after the URL tag, but before the dependencies tag.

After this, run the following maven command:

mvn clean compile assembly:single

This will output a jar-with-dependencies.jar file in your target\ directory.