Friday, December 30, 2011

How do you deal with coder's block?

I've kind of fallen into a trap with my Ruby work. I've been working on Dungeon Crawler for so long that I'm getting sick of it. I've had help from several friendly Rubyists (@jqr, @mileszs, @netshade, I am looking at you here) and I simply can't figure out how to make a proper redirect based on a form input.

This is extra irritating because I'm pretty sure I DO get how routing with Sinatra works, but starting a user out on one page with an input form, then redirecting that user to another page based on his input, seems to be escaping me.

I've gotten this to work in a limited capacity, when all of the logic is thrown into the

get '/input' do

method, but using a case/when statement here always uses the same logic. For example, dais_room will be north of torch_room, but vine_room will be north of dais_room, and I was always being redirected to dais_room with input "go north."

I also had a problem of simply being redirected to a white page with black text pulling the description of the room. I believe this was the method @netshade showed me for automatically creating a room without explicitly coding it, but for some reason it was not loading a view file.

Here's a full gist of what I've got, if anyone wants to give me some srs help:

Dungeon Crawler full gist

What do you guys do when you get so frustrated with a project? Do you power through, work on something else, or just take a break? I feel like since the holidays began, I've found a ton of great excuses not to code. It's Christmas Eve! It's Christmas! I just had LASIK surgery done!

But I'm sick of making excuses and I want to get back into working on a project without feeling like a gigantic dummy or just tearing my hair out because I can't figure it out. That makes sense, right?

It's not all bad news, though. @netshade and @annamul gave me The Pragmatic Programmer, a philosophical/theoretical book about coding. I really like the PragProg guys, and this book has been a lot of fun to read so far.

I think I need some way of setting goals for myself each week with coding. As in, "This week get better with using Git for source control," or "This week, get more comfortable with Javascript." Any recommendations for simple goal setting applications, or methods you've used? I use Tadalist for simple day-to-day chores and things, but that's not quite what I want. Maybe Evernote would work? I still haven't checked into that.

Either way, thanks for all your help, everyone! And Happy New Year!

Wednesday, December 21, 2011

Working with the Method method in Ruby

So with the help of my friend Z (also known as Chris to some, mostly just his wife) I've made some progress on Dungeon Crawler. But not much.

Namely, he showed me how to abstract my routing, so rather than having

get "/torch_room" do
  @torch_room = torch_room
  erb :torch_room

I have a method that automatically builds a route based on methods that already exist for rooms. Pretty awesome! I think learning to be less specific and abstracting my code is one of the most difficult things I'm learning. One of the guiding tenets of Ruby is DRY (Don't Repeat Yourself) and I really just need to be aware when I'm writing the same basic code more than once that it can probably be abstracted.

Ok, but here's my problem. I still can't figure out a way to collect input from a form, pass that input into an instance variable so that I can check it from other rooms and perform redirects based on the input itself. Does that make sense? I am absolutely trying my hardest to be clear about what I'm trying to do. Z also clued me in on a Method method but I can't figure that out, either.

Here's a gist with what I've done so far, but (FAIR WARNING) it's straight up busted:

Busted Gist

That said, I've noticed a funny thing about this problem. Bear in mind I've been wrestling with this guy off and on since my last post. (I DID do a couple of fun tutorials in between wrestling matches, mostly to keep myself limbered up) I didn't get frustrated in the usual "FUCK IT I GIVE UP" kind of way, but more in a "huh that didn't work. Ok let's try another thing. Hmm nope, that didn't work either," kind of way.

I did try some CRAZY other things, based on what my friend Miles told me about last time I posted about this problem (said crazy things mostly involved working with hashes, trying to convert hashes to strings, etc. Does that work? PROBABLY, I DON'T KNOW!) with minimal success.

I think this is how Daniel-san felt when he realized the entire time he thought he was washing Mr. Miyagi's car, he was actually learning karate.

Tuesday, December 13, 2011

Trouble with Ruby form methods

I'm still working with my Dungeon Crawler Sinatra app. Believe it or not, I have a problem. I'm trying to get a simple form method working to allow a user to move from one room to another by typing in the direction he wants to move and then hitting 'Submit'. So good so far, right?

Here's a link to a gist of the code I've got so far:

Working with form methods

The second file I posted in the gist is code that works, but I'm looking for a cleaner way of manipulating the information collected from the form method. Does that make sense? This is probably easy enough to do, and @jqr gave me some help with it last week, but I can't figure out how to make these form methods behave.

On a side note, do you have a problem with getting distracted with new ideas for projects when you're in the middle of a project? This seems to happen to me all the time, and I've been handling it by saving as much as I can think of in a Google Doc. I wonder how other programmers handle this? Do you just write things down in a notebook? I've been thinking about creating a template to use for these project ideas, just to keep my thoughts a bit more organized. If any of you have a template like this, or suggestions on what would be key features, I'd love to hear them.

I actually think a simple drawing application that allows me to add notes and save to the cloud would be ideal, but I haven't heard of anything like this.

Wednesday, December 7, 2011

More work on Dungeon Crawler

So my current project is coming along pretty well. I had an "AHA!" moment the other day (partly thanks to @jqr's hint about how to interpret gets.chomp) when I realized I need to use a form to collect that data. Once I've actually GOT some input from a user, it's easy enough to manipulate that information and make things happen.

I've drawn out the map of the entire dungeon (to help with actually laying it out when coding) and I've written methods and routes for all the rooms. Currently I'm loading a separate view for each room, since I eventually plan to have hand-drawn images representing the rooms themselves (which get updated when things happen, such as chests are opened, items discovered or moved, etc) so I thought this was the best way to handle it.

I've thought of ways to do the entire dungeon with a single view file and simply loading different information when the player makes certain choices, but for now I'm leaving that for a refactoring. Strangely enough, I think the hardest part of doing it this way would be figuring out a method for changing the image that represents the room, not the actual routing or the get method that would change the room. Strange!

I'm also not worrying about the individual features of rooms just yet, such as locked doors, traps, monsters and so on. My immediate goal is to be able to move throughout the entire dungeon, making sure all the routing works correctly and that you can't move into a room you shouldn't be able to.

Sinatra has proved a lot of fun to work with, in addition to being incredibly simple. It's kind of fun to have to do my own routing, too.

Also, I think it's important to name a project, so I'm calling this one Dungeon Crawler. (This was always the name of this project, even when it just lived in a Terminal window, but I'm not sure if I've mentioned that here or not)

Finally, I learned a great trick. I'd originally named my .rb file "dungeon_crawler.rb" and it quickly became tedious to type "ruby dungeon_crawler.rb" in the Terminal every time I make a change and have to reboot Sinatra, so I renamed it to "dc.rb". Much less tedious! My guess is that coders learn tons of tricks like this over the years.

Sunday, December 4, 2011

Making a web game with Ruby

Tonight I sat down to work through a bit more of Learn Ruby the Hard way (seriously, I'm on lesson 47 out of 52, I really should just finish it) but it didn't take long for me to get antsy to work on an actual program. Here's my current idea:

Building on AAN and Skyrim Stories, I want to take the dungeon crawler I made back in the summer, add some "awesome" hand-drawn graphics, and make it playable online. So far I'm picturing this as a Sinatra app, since it's pretty small and I won't need a database, and I can use Yaml for room descriptions. I've thought about ways to display different graphics for rooms when certain events happen, and I need to figure out how to take input from a user when an application is running on the web.

How do you collect information from a user, manipulate it, and trigger other functions based on the input when an application is running on the web? I'm unclear as to what the web equivalent of input = gets.chomp() is.

This project is largely just an excuse to take code I've already written (for the most part, it'll have to be refactored a bit for the web) and get more comfortable with getting a Ruby application to run on the internet. On top of that, I'm big into video games myself, and I'd love to have a hand in making games. Ruby probably isn't the best choice for making a game, but whatever!

Monday, November 28, 2011

Random Video Game Name Generator with Ruby

I've been working with a LOT of Javascript lately. And when I say "working with," what I mean is "finding scripts that will do what I want them to do and modifying as necessary." Wait, isn't this supposed to be a Ruby on Rails blog? What happened!?

I got back to work on my random video game name generator tonight. I basically wanted to style it a bit and find a way so that it would generate a new phrase whenever the page is reloaded and then provide a link to reload the page. Pretty easy to do with a Javascript code, but I'm not a huge fan of reloading the entire thing just to reload this bit of text. Probably a better way to handle this, right? Maybe an Ajax call? What do you guys suggest? This works but I don't like the look of it, I guess.

Anyway, here's a link to the app on Heroku:

Random Video Game Name Generator

I wanted to accomplish a few things with this project. First off, build a random name generator with Ruby, and then figure out how you run that code on the web. This was largely a matter of learning Sinatra, and when I say "learning," I mean reading a tutorial and talking to @jqr about it for a few minutes. Sinatra is like SO easy.

I've got plans for how I could expand it (don't I always? Other coders have this problem too, right?) such as allowing users to save names they especially like, then enter a short description of what the game would be like. Viewers could also look at games that had been saved, perhaps vote on them, look at most popular games, etc, etc.

I think it's getting easier for me to think about WHAT applications COULD do, now that I know a bit more about HOW they're built. That makes sense, right?

Sunday, November 27, 2011

More work on Skyrim Stories

Today I finished up Skyrim Stories. If you'll recall, last time I posted about this project, I was looking for a way to strip out #skyrimstories from the posted tweets as well as a way to make the usernames into links to that poster's Twitter account.

My friend Matt sent me to W3 Schools to learn how to use string replace with Javascript. Took me a minute to figure out how this worked until I realized I needed to call a string replace method on the strings BEFORE they were collected into an array.

I was able to use Twitter Anywhere to make usernames into links. Plus it's got a slick hover card feature with a +Follow button. This API is easy to understand and did exactly what I wanted done plus a few extra things.

For the most part I think I'm done with this project now. I might tweak it a bit here and there, but I think it's pretty solid for what it does. And it's time for me to get back into some Ruby work, anyway.

Thursday, November 24, 2011

Working on Skyrim Stories

So I've been playing a lot of Skyrim lately. I mean a LOT. It's interfered with my coding schedule a bit, but I've also been working on a Skyrim-related project.

Take a look:

Skyrim Stories

Basically what this site is doing is searching Twitter for tweets tagged with #skyrimstories, and displaying the 15 most recent Tweets. My friend @netshade sent me the javascript for it, and my friend @jqr got the domain set up and (gently) harassed me to work on it.

So far I've had a lot of fun with this project. It's been good for me for a few reasons: first, the time between thinking of the idea and having a working first version was about 2 hours or so. Within a few minutes of calling @jqr for advice, @netshade had already sent me the code and @jqr had set up the domain. It feels good to get work done really quickly, especially since I sometimes feel like it takes forever for me to get ANYTHING done. It's also been a good opportunity to get my hands dirty with some CSS and I always enjoy styling. And lastly, it's reinforcing what I've known for a long time: programming is programming, and it doesn't make sense to use Ruby or Rails for every project, especially if there's an easier, more elegant solution.

A few notes here: First, I've got very limited experience with Javascript. I can typically take some code, figure out how it works and manipulate it to do things I want it to do, but I can't write my own. For example, the code @netshade sent me worked pretty well, but it was displaying user names instead of users, so instead of displaying a tweet from @illbzo1, it would display it as being from Tyler Moore. The code also displayed retweets by default, but a quick look through Twitter's Get Search API and I was able to fix that. Especially at this stage where I'm not paginating older tweets, I don't want the entire feed to get populated by retweets. And retweets don't really fit with the idea of this site, anyway.

I didn't invent #skyrimstories, but it's already (kind of) popular, so I think with a bit of promotion and some more polish, this could really be a fun site. At least until everyone gets sick of Skyrim, but that'll be another few months, at least.

I've still got a few things I want to do with it. First off, I want to strip out #skyrimstories when the tweet is posted to the site, because I think it'll read better without that Twitter-specific language. I'd also like to make the username displayed with the Tweet a link to that user's Twitter account. I'll also want to look into a way to paginate older Tweets, displaying 15 per page or so.

Anyone with more Javascript powers have any advice?

Here's a link to the project on GitHub:

Skyrim Stories on Git

Wednesday, November 9, 2011

Finished random name generator in Ruby

I've finished up a working version of my random name generator. Here's a gist of the code:

Random Name Generator

I'm calling it aan (short for adjective, adjective, noun) because the original was just three phrases slapped together. Now I've added functionality that will generate a prefix or a suffix (seemingly) at random. I might spend a bit more time working with this. It's been a fun little project and I'd like to make a Rails project for it so I can put it up on Heroku and show it to non-coders.

Some other things I may look into:

A way to output the full name on a single line. I tried print instead of puts, but it simply outputs the pieces of the array, not the entire string built from the various arrays.

A way to capitalize every word except for words like "of", "the" and so on.

Using this with other data. What about a Full House episode plot generator? What if instead of specifically saying "Uncle Jesse takes Stephanie to the movies, which makes DJ incredibly jealous" I had "DAD takes DAUGHTER1 to the EVENT, which makes DAUGHTER2 incredibly jealous" and I passed in variables, to further randomize output? Maybe this will be my next project. It kind of combines stuff I was doing with the MadLib generator and this random name generator.

One of the things I like most about Ruby is how much you can do with it once you have an idea of what you're doing. I've definitely got a better idea of how reading files and using data found in those files works now. It's also pretty awesome to sit down for a couple of hours and bang out a working program.

I've also found that since I've become less focused on making a career change and more interested in learning how Ruby works, I'm having a lot more fun coding. That's a plus, right?

Monday, November 7, 2011

Random Name Generator with Ruby

I like making stupid things with Ruby. Last week I was working on a MadLibs generator, not because I have an uncontrollable urge to make MadLibs, but because it was a project I could understand and I wanted to build.

My friend Eli showed me how to refactor the code so it was less specific and therefore much more versatile. Whereas the code I wrote was very specific to one MadLib, the one Eli helped me write is far more general, and can make MadLibs out of any text file that's been prepared (substituting all instances of a noun with NOUN, or NOUN1, NOUN2, etc, for repeating nouns)

It's obvious to me how valuable separating logic and data is, but it's going to take some work for me to really wrap my head around this. I've been coding with my logic and data entwined in a big hot nasty mess for a while.

Here's a gist of the finalized, objectified MadLibs generator:

MadLibs Generator

So my next goal is to take what I learned with refactoring the MadLibs generator and make another stupid project. I ran across this site a few nights ago:

Video Game Name Generator

So I've decided to build one using Ruby. I'm calling it aan so far (adjective, adjective, noun) and I've got a version working that will generate random combinations from pre-defined arrays, but I'm working on expanding it so it will read text files and generate lists from those files.

Once I get THAT up and running, I want to work on making it a bit more complex. Adding support for generating names that may or may not include a prefix or a suffix in addition to the standard adjective-adjective-noun, for example.

I think I'm having a lot more fun with coding when I'm working on stupid things like this than when I was working on larger-scale projects (long tutorials, Manticore, Chorenivore) but it's hard for me to objectively say which is more valuable.

Sunday, October 30, 2011

Refactoring Ruby Code

Since I've been working on this MadLibs generator, I've been through a couple of refactorings. Friday night, I got the code hammered out but I ended up with this:

MadLib Generator, first version

It works, sure, but it's ugly. A ton of gets.chomp()'s, and there's obviously a better way to do it. Still, my plan was to hack it out as best I knew how, identify problems with it, and then rework the code.

So here's my second attempt:

MadLib generator, first refactoring

Not bad! I've gotten rid of all the gets.chomp() commands in favor of loops that will collect the correct number of nouns, verbs, adjectives and so forth. I also got rid of the prompt method - it's a hold over from the dungeon games I've been working on and I felt it was unnecessary. I was pretty proud of this, but my friend Eli thought it could be refined further, suggesting I try to Objectify the code. I'm a bit puzzled by this. What does this mean?

At any rate, I took another look and here's what I've got now:

MadLib generator, second refactoring

In this iteration, I cleaned up what's being collected a bit, and took out the definitions for popping words out of the arrays. I realized I could just call the .pop method directly by defining the array as an instance variable. This way, I was able to shorten the code by several lines by adding a character to each variable. Pretty good trade off, if you ask me!

I also redefined each array after calling a .reverse method on it. Since I'm using .pop to pull words out of the array to place in the Mad Lib, this will keep the words in the same order the user entered them.

Things are going pretty well. I feel proud that I'm anticipating problems and finding solutions for them now. Also, I should've been using Gists for a long time now.

Friday, October 28, 2011

Require - No Such File to Load Ruby

The exercise I'm working through in Learn Ruby the Hard Way has me spending a week creating my own game. I've been building various text-based adventure games, but was stuck on what to do next. This morning on the way to work I got the idea of building a MadLib generator.

The way I picture it working is like this: the generator will ask the user to select a Mad Lib from a list, then ask for the requisite input (nouns, adjectives, verbs) depending on the Mad Lib selected and finally spit out the finished product. Simple, right?

So my thinking is this project would be split into two parts: the main program that asks for which Mad Lib the user wants to do, and the Mad Lib that is loaded upon selection. To get this up and running, I decided just to make one Mad Lib work at first, then add support for multiple Mad Libs and the ability to choose between them.

This is just a simple matter of requiring the Mad Lib file from the Main file, but I ran into a small problem.

Using the require 'mermaid' command threw this error:

<internal:lib/rubygems/custom_require&rt;:29:in `require': no such file to load -- mermaid (LoadError)

I wasn't sure why this wasn't working, since I've used require to load separate .rb files before. After a bit of digging around, all I had to to do fix this problem is change require 'mermaid' to require_relative 'mermaid'. This makes sense - both files are in the same directory, so this command is simply saying to require this file located in the same directory as the main file.

On a side note, I'm glad to have fixed the problem, but I'm getting to the point that I think it's better to understand WHY things don't work, rather than finding the solution and moving on. Can anyone tell me why 'require' wasn't working, but 'require_relative' does? Is it an older style of Ruby code that's outdated? Do I need to change some configurations? Is require_relative a workaround? Where does require look for files, if not in the same directory the file that's making that call is located?

Anyway, it felt good to make some progress on this tonight. It's pretty awesome that I can come up with an idea on the way to work, come home and put it together in an hour and a half or so. I think this will be a fun little project. I plan to work on it more this weekend, expanding it, polishing it up and so on. Here's a link to the gist I made of it:

MadLib Generator

Wednesday, October 26, 2011

Initializing Classes in Ruby

I definitely tend to jump around a bit when it comes to learning to code. I was working on Manticore quite a bit, then jumped into Learn Ruby the Hard Way, and now I've hit a bit of a snag so I checked out Code School and the introductory Ruby lesson. (This lesson is based on Why's old lesson, by the way, and is awesome so far) I'm a big fan of Code School so far, because hands-on, practical tutorials have always been one of the best ways for me to learn.

Much like Learn Ruby the Hard Way, it's a lot of review, but I've been interested in seeing what Code School has to offer for a while. Not to mention, switching gears slightly seemed like a better use of my time than sitting around frustrated because I wasn't understanding defining Classes and initializing them properly. I also think the more time I can spend having fun with Ruby, the better. I end up coding longer and enjoying it more, which leads to me learning more and it all kind of snowballs from there until I can build a sort of half-ass snowman with string literals for arms and instance variables for eyes.

Still, Ruby isn't all string methods and arrays, so I'll get back to my problem with Learn Ruby the Hard Way pretty soon. Probably tomorrow!

Here's the basic problem: I have one Class, Game, and the extra credit for this particular exercise is to break the Game into two Classes: Engine and Map.

Here's a link to a gist of what I've got:

Gothons Attack!!

What I'm assuming I need to do is break the rooms a player goes through (methods such as :central_corridor, :bridge_access, etc) into the Map method, and put the code that drives the game into the Engine method. So now I need to learn what initializing a class does, how to do it, how to call a method in one class from another class, and how to make two classes work in concert. For example, Engine will be starting the game (I assume) and moving the player through the rooms that are defined in Map (I also assume) Any input on this problem is, as always, HIGHLY appreciated!

I used to think of learning Ruby as unearthing this huge artifact, but now I think of it as being inside of a mostly darkened room, where I'm stumbling around and looking for switches. Once in a while, I flip a switch and it might illuminate a far off corner, or a whole corridor, or just a tiny little piece of the room. Does that make sense? Or in other words, learning how to do new things is really frustrating right up until it's not, and then it's awesome.

Sunday, October 23, 2011

Here documents in Ruby

I'm still working through Learn Ruby the Hard Way, and the last few exercises have been about building simple text based dungeons. You may recall I spent about a week working on one of my own. This latest exercise introduced me to here documents.

A here document is an easy way to display a long, multiline string. This would have been PERFECT for use in my dungeon adventure. Here's how it works.

This is the original description from the first room in the dungeon game I built:

  puts "This room is dimly lit by two sputtering torches."
  puts "There are three doors leading out of here."
  puts "What do you do?"

You may notice a few "puts" methods. It's not terrible in this case, since I'm putting several small statements, but it's tedious to type and unnecessary to use so many methods when you could do it with one here document. So forget what I said. There's a better, simpler way to do it, so it IS terrible!

So this example can be re-written like this:

  This room is dimly lit by two sputtering torches.
  There are three doors leading out of here.
  What do you do?

You begin the here document with <<−TORCH_DESCRIPTION and end it with TORCH_DESCRIPTION. Ruby interprets everything in between as one string. Cleaner, right? Easier to read? Who wouldn't love it!

On a side note, you CAN write this as <<TORCH_DESCRIPTION instead, but by adding the minus sign, you can indent the code as usual. Without the minus sign, the terminator can't be indented, or else Ruby will start complaining about "can't find string TORCH_DESCRIPTION anywhere before EOF".

So I recommend using the minus sign. One more character makes your code a lot easier to read. I also ran into another little problem. Since a here document is a string literal, any variables won't be interpreted correctly. This is where interpolation comes into play. Here's an example from the current exercise I'm working through.

guess = gets.chomp()

if guess != good_pod
  puts "You jump into pod %s and hit the eject button." % guess
  puts "The pod escapes out into the void of space, then"
  puts "implodes as the hull ruptures, crushing your body"
  puts "into jam jelly."
return :death

This bit of code describes an escape pod room, where the user has to pick an escape pod to use. So we set the user's choice as "guess" and then call it in the method below. This is what happens when a user chooses poorly. However, if I were to rewrite the code using a here document, this is what I'd have:

  puts <<-BAD_POD
  "You jump into escape pod %s  and hit the eject button. %guess
  The pod escapes out into the void of space, then
  implodes as the hull ruptures, crushing your body
  into a jelly."
return :death

Now the %s and %guess won't be interpreted as variables, since they're inside of a string literal. Luckily, there's an easy solution: interpolation. Just swap out the %s for this little guy:


Ruby will look at this, understand that means you want to use a variable inside of a string literal, and then pull the information it collected when it asked the user which pod he wanted to jump into.

I'm hoping this post will be helpful for others who are grappling with here documents. It took me a bit of digging to figure out how to get the code to index properly (since it looked awful in Textmate, and my solution was to put the string in quotes, which was unnecessary) and I needed to figure out how to call a variable from inside the here document.

Sunday, October 16, 2011

Finished text-based adventure in Ruby

I'm now more or less done with the text dungeon I was building last week. I finished it up last night and fixed some bugs, refactored a bit and made the game more playable today. I also ran the code with -w, which shows a list of warnings. I'm not entirely clear how warnings differ from errors (other than errors stop the code, whereas warnings allow it to continue) but running the code this way allowed me to clean up bad indentation (plenty of it) as well as cleaning up a few other things. I also found out you can indent or unindent (is this a word?) a block of text in TextMate using keyboard shortcuts. Of course, I only found this out after getting frustrated at how long it took to manually indent or unindent a block of code. What's the lesson here? Sometimes it's not about learning new tools, but learning to be more efficient with the tools you already know. 

I've learned a lot with this little project: defining instance variables such as @brass_key, using instance variables to do things within other methods, such as opening doors, creating an inventory for the player that adds or subtracts items as they're found or used, logic to change events if certain instance variables were true and so on and so forth.

Tomorrow I plan to get back to work on Learn Ruby the Hard Way, but this week has definitely been well spent. I may revisit this project in the future and rewrite it to use case / while instead of if / elsif, but I'm ready to work on something new. I spend a lot less time flailing around and feeling stupid now and a lot more time coding or looking for ways to do what I want to do. 

My vocabulary is getting better, too, so it's easier to find information now. And all of this work makes me think about Manticore (don't worry, baby, I haven't forgotten about you!) and how much easier it'll be to redo now. The code I had before I sat down with Eli a few weeks ago took me a couple of months to write, and I'm pretty confident I can get the same functionality with less code in about a week now. But first I need to finish up Learn Ruby the Hard Way. 

And I've been thinking about using what I've learned to write tutorials. I'm sure other new Rubyists will be confused about local and instance variables, or how to write and call methods, and I'd like to try and write something up that will explain these basic ideas in the context of a text-based dungeon crawler. I haven't thought too much about it yet, but it's something I'd like to do in the future.

Here's a link to a gist of the game:

Dungeon of Unfathomable Horror

Tuesday, October 11, 2011

Calling a method in another method in Ruby

I've hit another turning point in my work with Ruby. I've slowly been getting more and more excited about coding, but this week marks the point that sitting down to code seems like something that's fun to do and not just something I kind of enjoy doing that I'm working on because I'm interested in a career change.

I had a really good day with the project I'm currently working on as part of Learn Ruby the Hard Way: a text-based adventure. It's a pretty simple concept, but so far I've got a working four room dungeon. And it's a game! Sure, it's a basic, text based game, not even as complicated as Zork, but it works! Do you know how awesome it feels to build something that works? REALLY AWESOME.

Today at work I was thinking of ways to expand it. How about adding a "help" command to give players some commands that will allow them to manipulate objects in the dungeon? How about a "look" command to remind players which room they're in and to point out important features of that room? How about a "quit" command to let players quit the game?

Done, done and done. Pretty easy: these were all just matters of defining methods and then calling them within the methods I've defined for the various rooms. For example, here's the "help" method I made:

def help()
  puts "Here's a list of handy commands to help you in your quest:"
  puts "Open: open doors, chests, your heart, etc."
  puts "Look: get a description of the room you're in."
  puts "Take: take an item and add it to your inventory."
  puts "Inventory: see what items you're carrying."
  puts "Quit: quit the game, as a coward would."

And then I wire it up in each of my room methods, so in the torch_room method, I use this code to allow a player to call up the Help menu:

if next_move == "help"
  prompt; next_move = gets.chomp

As I may have mentioned before, I don't have much coding experience with other languages, so I don't know how easy it is to add functionality, but it's really easy with Ruby, and that's part of what I love about it. I'm having a ton of fun with this little project, and while I did a similar project when I was working through Beginning Ruby, those were different times. It was a matter of simply copying code at that point and not understanding what I could do with Ruby and how to make it do what I want it to.

I'm not saying I've mastered Ruby (not by a long shot!) but I'm definitely getting better and it's getting more fun the more I learn. My goal is to keep working on this dungeon for a few more days, expanding the number of rooms, adding monsters and traps, coming up with an inventory system and so on before I move forward with Learn Ruby the Hard Way.

Monday, October 10, 2011

Scope issues with Ruby

I'm still working through Learn Ruby the Hard Way. The exercise I'm working on now has me building a text-adventure dungeon (similar to the one I made when I was going through Beginning Ruby) but this time around I've got a better idea of how to map the project out.

Basically I'm starting with a simple 4 room dungeon. Players will need to go to one room to get a key to unlock a door in the starting room. I understand how to build rooms and allow a player to navigate between them, but managing an inventory and allowing players to access different rooms once they have completed a specific action (such as finding a key to unlock the door) was confusing me.

After asking for some input on Stack Overflow, I think I've got a better handle on the problem now. I'd originally set door_open = false in the start_room method, then once a player had found the key in the chest_room method, I set door_open to true. However, I couldn't call this from the start_room, because it was a local variable. As far as start_room was concerned, door_open was still = false. Am I thinking about this the right way?

I'll simply make key into an instance variable, so it can be accessed by all methods, and edit the logic so while !@key_present, players can open the door. Easy enough! Just wish I could get to coding NOW instead of tonight.

Also, I've been using if/elsif statements, but the same user suggested case/when is cleaner and simpler. I haven't used case/when before, but from the snippet of code he posted, I think I agree. Your thoughts?

Sunday, October 2, 2011

Using Ruby to Solve Problems

This past week I've been working through Learn Ruby the Hard Way. It's really a great resource (as I've mentioned a few times already) and I'm picking up lots of good habits. Here's a little example:

I work full-time doing SEO for an e-commerce site, and a while back we ran into a problem on our site with duplicate content. We needed a simple tool for entering two blocks of text and calculating how similar they were as a raw percentage. We eventually found some tools, but they weren't quite what we needed and weren't that great.

So I got the idea of building something using Ruby to do just this and spoke to my friend Eli about it. I still haven't actually BUILT this little program (and I'm sure it WOULD be little, at least at first) and part of the reason was that I didn't have a great idea of HOW to build it. I assumed I might have one model, say Text, with two textarea fields that could be compared, then spit out a percentage for similarity.

Obviously, I'd be using Ruby to make this calculation and that would be a matter of defining a word, counting instances of words, and then making a comparison between both blocks of text.

I've been doing a lot of work using Ruby to open and edit files, so it's obvious I could do similar operations to open and compare files, then generate a report based on that comparison. Not an elegant solution, since users would want to paste text into fields and compare them, not upload files to compare. But I'm sure it's doable. So that might be my next project.

I kind of tend to bounce around between projects, but I'm learning the entire time, so I don't feel bad about it. That's what these projects are for, right?

I also tend to think of an idea, and immediately think of ways to expand it even before I have the original idea working. For example, I'm already thinking of how this project could be expanded to do other things with text, such as identifying words that are used too frequently, identifying passive voice, identifying and suggesting replacements for adverbs and so on. In this case, I think it's because the original problem seemed to be "How can we identify content that's too similar in terms of SEO?" but I've begun thinking of it as "How can we write better content for the web?"

From my limited experience and understanding of web development, programming and computer science in general, it seems to be a matter of identifying a problem and then finding a solution. Am I far off the mark here?

Tuesday, September 27, 2011

Learn Ruby the Hard way

So I was all amped up and ready to get back to work refactoring Manticore tonight, but I ran across this site last night:

Learning Ruby the Hard Way

I've been meaning to beef up my Ruby skills, and although this site is largely review for me, I think it's GOOD review. I'm definitely getting in the habit of commenting on my code, which is something I've been meaning to do for a while now. I'm already through the first four exercises, so I don't anticipate this taking very long to get through.

When I first started learning with Beginning Ruby, I read through a bunch of Ruby code, but it wasn't very practical, since I had yet to get my filthy mitts on Rails. And now I've been hitting Rails pretty hard for a few months, and while I've used Ruby here and there, I've been feeling like I needed to get better acquainted with it. So here we are!

This is a good resource, and I wish I'd found it (or it had been available) when I got started. It's well written, engaging and doesn't hold your hand too much. The author assumes you can do some basic things, such as researching terms you aren't aware of and figuring out why an error happens when it does.

Monday, September 26, 2011

Updating to Rails 3.1 and Ruby 1.9.2

Yesterday evening I went over to @jqr's house for some Rails help and advice. Early into out discussion it became clear to me (and was probably already clear to Eli) that I should redo Manticore.

Here's where it stands now: A whopping 14 models. 14! Why, Tyler? Why did you do that?

Back when I first started working on this project (in April or May I believe) making things that belong_to a Character, such as Hit Points, Armor Class, Statistics and the like, into separate models made more sense to me because they would be easier to edit. It didn't occur to me that if I only wanted to edit a Character's Hit Points, that I could simply render a form that ONLY had that field on it, and edit the record that way.

So after about 3 hours of talking and eating delicious cinnamon buns, @jqr showed me how to think about the problem in a different way. Rather than having modifiers that are specifically called from Statistics and applied to things like Fortitude Saves, or Attack Rolls, I'll have one method for ALL Modifiers, not a thousand different kinds of modifiers. I'm still rolling this around, trying to get a grip on it, but now that I've begun thinking about Manticore in a different way, I think I'll be able to make much more progress going forward. I already GET how to define methods and call them, as well as how to render partials and views that do a variety of tasks, so I'm most of the way there already, right?

Most of my time tonight was spent trying to get Rails 3.1 and Ruby 1.9.2 installed and cooperating. I was getting a ton of BOGUS errors, about Gems that Rails couldn't find. Turns out you have to install a bunch of crazy stuff for 3.1, like Sass, Sass-Rails, Coffee-Script and so on. WEIRD, right?

One cool thing I noticed: I went ahead and created a scaffold for my Character model, and made statistics into attributes of Character. All the statistics are integers, so when it pops up on the form, you get an automatic drop down that just inputs numbers. I'm guessing this is to get around people entering non-integers, and I bet I can pretty easily limit the scope of these attributes.

I don't think updating to Rails 3.1 and Ruby 1.9.2 was strictly necessary, but this seems like a good time to make a change. Also seems like a good time to get more comfortable (re: comfortable at all) writing and running my own tests, considering that's something I've woefully neglected.

Wednesday, September 21, 2011

Instance variables and local variables in Rails

I've got a lot to learn about local and instance variables. I already knew 'character' meant a local instance of character, but I thought '@character' referred to another model, and not an instance of the Character model. I knew that sometimes if Rails was complaining about an unidentified local variable, putting an @ in front would often fix the problem, but I didn't know why. I think I've got a better handle on this, but I think the time has come to do some serious background reading to try and patch up some of the holes in what I know and what I think I know.

On the other hand, thanks to help from @jqr and a healthy does of trial and error, I've gotten that pesky statistic bonus problem figured out. This is what ended up working:

def total
  fortitude_base + character.statistic.con_modifier + magic + misc

And here's the con_modifier definition from my Statistic model:

def con_modifier
  (constitution.to_i - 10) / 2

I'm keeping it as .to_i now, as a fix for a case where a player tries to create a Fortitude save before a Constitution score has been entered. The .to_i translates a nil record to 0, so Rails does a temporary calculation (which isn't shown) rather than displaying an error. Not sure if there's a better way to handle this (perhaps simply checking that statistic.constitution.present? before performing any calculations) but it works for now.

More importantly than simply figuring this one instance of how to define logic in one model and then call it in the view of another is understanding HOW it works. I can extrapolate these methods and apply them to other things: skills, attack rolls, armor class, etc, etc. Once again, Manticore proves to be a useful learning tool! SUCCESS!

Sunday, September 18, 2011

Nil can't be coerced into Fixnum in Rails

Question time!

I'm trying to figure out a way to calculate bonuses or penalties from a Character's Statistics, and then apply that method in other Models' views to calculate things like Fortitude saves, attack bonuses and so on. I've been working with a modifier for Constitution and here's what I've got so far.

The logic for calculating a Statistic bonus/penalty is (statistic - 10) / 2. So for a score of 14, we get 2, and for a score of 8, we get -1. Not bad so far!

So I define this method in Statistic controller:

def con_modifier
  (constitution.to_i - 10) / 2

And since I want to see it in my Character view, I wire it up in the Show method in Characters controller as such:

@con_modifier = @character.statistic.con_modifier

So I can see it in my Character view (where most of this information is displayed) and I know it's working so far. I've got a Fortitude model for Fortitude saves, and I'd like to use the con_modifier in the logic to calculate a total. How do I call a foreign model correctly this way? I have:

Here's the logic for calculating a total in my Fortitude model right now:

def total
  fortitude_base.to_i + ability.to_i + magic.to_i + misc.to_i

And I tried changing it to:

def total
  fortitude_base.to_i + @con_modifier + magic.to_i + misc.to_i

But then I get this error:

nil can't be coerced into Fixnum

So obviously it isn't calling up the correct information. I've noticed if I chage @con_modifier to @con_modifier.to_i, it calculates it at 0, because it's nil. Any ideas on how to call the number that actually exists? Do I need to define it in my Fortitudes controller as well, or can I simply define it in the Fortitude model and call it in the view that way?

Tuesday, September 13, 2011

Validating integer ranges in Rails

Taking my friend Matt's advice, I redid the validation and logic for my models in Manticore tonight. Didn't take too long and the new way makes more sense than before.

Here's what I had before:

class Initiative < ActiveRecord::Base   belongs_to :character   validates_presence_of :dex, :misc, :speed   validates_numericality_of :dex, :misc, :speed   def total     dex + misc   end end

And I've changed it to:

class Initiative < ActiveRecord::Base   belongs_to :character   validates_numericality_of :dex, :misc, :speed   validates_inclusion_of :dex, :misc, :in => -10..20, :message => "must be between -10 and 20."
  validates_inclusion_of :speed, :in => 20..200, :message => "must be at least 20."

  def total
    dex.to_i + misc.to_i

A pretty minor change, but here's what this is doing. First off, there's no need to validate both for presence_of and numericality_of an object. Validating numericality_of an object will in effect also validate_presence_of that object, since it must be an integer to pass validation.

Secondly, I've added a validates_inclusion_of to ensure that all integers make sense within Dungeons and Dragons rules. For example, :speed refers to how many feet a character can move per round. The vast majority of characters are going to be either 20 or 30, so I set 20 as the base. However, there are ways to get higher speeds, through class benefits, spells, magical items and so on, so I set the upper limit at 200. I don't use this object to make any calculations, but it's nice to have information that makes sense for a Dungeons and Dragons character, since Manticore is a Dungeons and Dragons character database program.

Lastly (and I think this might be a bit of overkill) I added .to_i to my logic, which will ensure all objects are integers before attempting to perform calculations. Am I right about this one? It also sets nil to 0, right? Pretty handy, considering I was wanting a way to set nil to 0 a while back.

I started to bang out a question, but as I was writing I got an idea of how to do what I want to do, so I'll give it a shot before asking for help

Monday, September 12, 2011

Code abstraction and models in Rails

I felt like I had a minor break through tonight, thanks in part to my friend Brent. Abstracting code using partials is something that's made sense to me for a long time. Basically, you're just cleaning up the code of a view by creating another bit of code that's called using a render method.

However, last night as I was writing some partials, I noticed I was loading quite a bit of logic into my view and it felt wrong, somehow. I felt...dirty. I was on the right track when I assumed there was a way to collect this logic into a method, then just call that method in the view, rather than having all the logic piling up, making an untidy mess of my code.

But I didn't quite get how to define a method in a model. Sure, I've defined methods such as:

def foo

But usually I got this code by following a tutorial, or reading through a book and so forth. It was never my code, and I think that was the reason I didn't really understand it. Now that a situation has arisen that I needed to learn how to write logic into a model and then call it in the view, I understand it. Funny how that works, huh?

Also, I don't think I'm quite as done with Manticore as I thought last night. I'm obviously still learning from working on it, and that's what I'm after. I've got some big ideas that are frankly a bit intimidating (user account creation and log-in, differing account types and permissions for dungeon masters and players, to name just two) but what's the best way to get over being intimidated by coding? By getting excited about coding. It's brought me this far, anyway!

Sunday, September 11, 2011

Code abstraction with partials in Rails

Abstraction was the name of the game tonight. As you many know, I have a _menu partial running across most of my pages. This partial links to a character, as well as his spells, skills, items and so on. I had a second area in the Character's view page that allowed users to add new pages, and the link would disappear once the page had been created. Why not move this create method up into the _menu partial and get it out of the Character's view page? That makes sense, right?

I thought so, but here was the problem. I had some text that said "Add:" with links for items, spells, skills and so forth. I didn't want either the text or the link showing up unless the page hadn't been created. Only showing a link_to method if that page hasn't been created is easy, but I couldn't figure out a simple way of only displaying some text if all pages that could be created hadn't been created. An easier solution would have been just to axe the "Add:" text altogether, but I like it as a bit of guidance and separation.

This may be a case of me understanding partials well, so every problem appears to be a problem that can be solved with partials, but here's how I wrote the code.

First, I created a new partial, called "_menu_create" and threw it in the Characters view folder.

Here's the code for the partial:

<%= link_to 'Items Page', character_items_path(@character) unless @character.items.exists? %>
<%= link_to 'Background Page', new_character_background_path(@character) unless @character.background %>

And here's the method for rendering the partial:

<% unless @character.items.exists? and @character.skills.exists? and @character.specials.exists? and @character.spells.exists? and @character.background %>
  <%= render 'characters/menu_create'%>

I feel like this is a bit over-engineered, especially since all it does that's different is not display the "Add:" text, but it works and I'm pleased with the result.

What's your opinion? Is there an easier way to do this? Is there also an easier way to group several conditionals together, so instead of writing the code as:

<% unless @character.items.exists? and @character.skills.exists? and @character.specials.exists? and @character.spells.exists? and @character.background %>

I could group all of these into a grouping called "conditions", and call something like:

<% unless @character.conditions? %>

Which would have the same effect? I'm guessing there IS something like this, and I just haven't run into it. I'm also getting the feeling I'm ready to move onto another project pretty soon, maybe running through more tutorials, or getting another book, or working on another personal project. Any suggestions? Should I keep working on Manticore? It's kind of hard to get a feeling for WHAT I should be working on, just that I should be working on SOMETHING. Crafting Rails Applications isn't quite what I was looking for, either. I was expecting something closer to Agile Web Development and it's more like a series of mini-tutorials, mostly for serious customization and I'm not quite ready for that jelly.

Thursday, September 8, 2011

Navigation methods in Rails

I may not always feel like coding, but most of the time if I sit down to code I get warmed up and quickly forget I didn't feel like coding. Today was one of those days. I didn't feel like coding, but I took a look at my to-do list and figured "Hey, I can at least knock out some of this easy CSS stuff, right?" I try to live by a code of "Rails every day".

With that said, here's a little problem I've got.

Here's how I currently have a Back link written in my Menu partial:

<%= link_to 'Back', characters_path %>

The problem is, I render this partial on every page, and so the Back link shouldn't always point to characters_path. I thought an easy solution to this would be to write the code like so:

<%= link_to 'Back', :back %>

This returns the user to the last page viewed, which is closer to what I want, but then I run into some irritating navigational issues. Say you were looking at a Character's Items, and created a new Item, then hit the Back button once it was created. Since I'm rendering the form in the Items view page, it simply takes the user back to the previous view, showing a form with blank fields. So here's my question:

Is there an easier way to handle this? A better method than :back? Should I simply make two versions of the menu partial, each with a separate back link? I don't think I'll need more than two. The menu partial rendered when viewing a Character will want to point back to characters_path, whereas every other page (Items, Skills, and so forth) will need to point back to the Character view page. Maybe I'm overthinking this, considering it's just an extra partial, but I'm thinking there might be a better way to handle this. Imagine if I wanted five different menu partials, or twenty? I think it's better to think of more abstract solutions that can be applied to multiple scenarios.

Wednesday, September 7, 2011

More has_one model work in Rails

When it comes to coding, it seems like I've got good days, bad days, and frustrating days. Sometimes the Venn diagrams of these days overlap quite a bit. Take today for example.

I've been coding now for a little over 2 hours and I've finally gotten a problem straightened out. If you'll recall, I was attempting to build a Background for a Character, have it show up in my menu partial, and editable from there. I had a method that would build models with a has_many relationship to Character, but Background will have a has_one relationship and it was proving a bit trickier. I've more or less got it straightened out now (at least it's working on my local machine) so I've thrown it up on Heroku.

Manticore on Heroku

I've also done some more work, simplifying the data that's actually displayed in the view, while still allowing users to manipulate that data with an edit action. My reasoning is a user may always want to know what his total Armor Class is, but how often do you need to know what your Deflection modifier is? Not often, that's how! So basically, if you're rarely going to need it, why display it all the time? I think eventually I'd like to have an arrow users can click on that might expand that information, while displaying the bare minimum by default. I'm not sure what I'd use for this, but it sounds like a problem for Javascript.

Also, don't mind those saving throws! They refuse to work. What a lazy model! This merits a bit of examination. And I actually just realized it's not working when creating a new character on Heroku. Thanks, Heroku!

Still, it feels good to have this problem figured out. I've been wrestling with it for a while, and now I can move on to wrestle with other, more interesting problems! Like this mysterious SAVING THROW problem that's arisen. What could be going on here?

Absolutely LOVE crossing things off my list. Although I appear to have added several more. As usual.

Monday, September 5, 2011

Difference between build_model and create_model in Rails

I keep a note pad with features I want to add, things I need to fix and other reminders to myself whenever I'm coding an application. I've got a few methods defined in my models that will calculate totals. Needless to say, these methods aren't going to do anything but complain if the data fields they use to calculate a total either don't exist or aren't integers. What to do?

Validation to the rescue! But I had a problem. A minor problem. The models I speak of all belong to a main Character model. Take my Initiative model for example. It belongs_to Character, and Character has_one Initiative. I have a few fields in Initiative: :dex, :misc, and :speed. These refer to a Character's Dexterity modifier, any miscellaneous modifiers and how many feet that Character can move in a round. So I have this method defined in Initiative.rb:

def total
  dex + misc

This way, I can simply call in a view and Rails will calculate the total for me. Cool, right? And this is where validation comes in handy. However, here's the issue I had. My validation worked, but it was showing an error BEFORE any data had been entered. Definitely better than not working, or allowing a user to enter a B instead of an 8, but I'd rather not show an error message if no error has been made. So what was the solution?

First, the validation I wrote, in my Initiative model.

validates_presence_of :dex, :misc, :speed
validates_numericality_of :dex, :misc, :speed

This all looks good. I suspected the error was in the way my new method was written in Intiatives controller, but I couldn't figure it out, so I asked for help on StackOverflow. User m_x was kind enough to point me in the right direction.

def new
  @character = Character.find(params[:character_id])
  @initiative = @character.create_initiative(params[:initiative])

This bit of code was the culprit. Easy enough to fix, though.

def new
  @character = Character.find(params[:character_id])
  @initiative = @character.build_initiative(params[:initiative])

It turns out the reason my validation was being called before a user had entered any data is because the create method creates a new object and attempts to save it. In this case, it wasn't saving because it failed the validation, because nothing had been entered yet. On the other hand, the build method creates a new object, but does NOT save it. Easy enough to remember! As an added bonus, this gives me some ideas on how to tackle another problem I've been thinking about.

This mistake feels like something I should have known before hand, considering how much time I've spent reading through the Rails API, but I have a hard time holding on to information until it becomes practical. But now that I've used this, and cemented exactly what the difference is between build_model and create_model, I won't make the same mistake again.

One less thing, right?

Wednesday, August 31, 2011

Alphabetical sort method in Rails

So the other day, frustrated with the complete lack of progress I'd made on trying to figure out how to link to a Background model from a Character's view, I decided the best thing to do is to work on some smaller problems until I either ran across a method that seemed like it would work, or INSPIRATO struck me, or I felt like battling that wily Background again.

One of the things I wanted to do is make it so when a user creates a list of Skills, they're displayed in alphabetical order. Sounds simple, right? And it is! Absolutely. But I had only the vaguest idea of how to write such a method (probably finding all the skills, then ordering them by name) and absolutely no idea how to call that method in the view.

So I headed over to Stack Overflow since this seemed like an easy enough problem that I could describe and get answered quickly enough. Who came riding over the hill like Gandalf, ready to save the day? normalocity! I have 0 idea who this guy is, but his method was clear, easy to understand and exactly what I was looking for. Have I mentioned how awesome the Rails community is, both locally and online? One of my favorite things about my learning process has been getting to know more people, and talking to more experienced programmers about Rails, coding and how things work in general.

So here's what I ended up doing. I first had to define the method in my skills_controller (which I had already done, and correctly too!) and then call that method in the view.

So here's the definition I came up with:

def index
  @character = Character.find(params[:character_id])
  @skill =
  @sorted_skills = @character.skills.find(:all, :order => :name)

Not bad! But then I got stuck. How do I call it in the view? Is it a separate thing? I've already got code that iterates over each skill and then spits it back out to the view. So was it a second call? That doesn't seem logical. So what about editing the code I already have, and calling the new method I wrote instead of the previous method?

Just one little change here. We started off with:

<% @character.skills.reject {|skill| skill.new_record? }.each do |skill| %>

And changed it to:

<% @sorted_skills.reject {|skill| skill.new_record? }.each do |skill| %>

So this code is doing the same thing it did before, but instead of simply bringing up @character.skills, it's bringing up @sorted_skills, which has already been defined as @character.skills.find(:all, :order => :name.

And this is just one example. I've got a crazy idea for a way to sort by two variables. For example, a Character will have class and cross-class skills. What about a way to sort these skills both alphabetically and by class or cross class skills? Nutty, I know! I'm letting that one brew for a while, though. Or what about spells? It might make sense to sort spells both by spell level and alphabetically. But you see what I mean? It's kind of getting impossible for me to learn something new in Rails without a) wondering how else I can apply it and b) wondering how I can tweak it, change it, expand it, pose it, scroll it, click it, or zoom it.

It felt really good to figure this out tonight, and even though this one instance is just a tiny fix that literally took two seconds to code, the logic behind it and understanding that logic reaches quite a bit deeper. After all, I'm not learning Rails to build Dungeons and Dragons character databases. I'm learning Rails to understand Rails.

Tuesday, August 30, 2011

Heroku and missing migrations

So my goal today was to dust off my Heroku account, throw up Chorenivore and Manticore, and then do a bit of coding. HOWEVER! Somehow a bunch of my migrations in my Manticore app were deleted, so getting rake commands to run on Heroku took a bit of finagling. And when I say finagling, I mean looking at my schema, rewriting the migrations and then applying them. Not a bad way to handle a migration that's gone MIA. I'm not entirely sure how this happened, but it's been fixed. This development process hasn't been the smoothest thing I've ever done.

Do you ever have this happen? You're looking at an older side project, maybe feeling a few pangs of nostalgia? Like "Oh, Chorenivore, I was so in love with you back in May! Where did we go wrong?"

I'm guessing probably. Or are programmers like sharks and can't look back?

Anyway, here's a link to my Heroku deployment of Chorenivore, my to-do list application:


A bit rough, sure! But I don't hate it. I kind of want to go back and work on some things I wanted to implement, but maybe some time in the future.

And here's Manticore, my Dungeons and Dragons character database application:


I also ordered a copy of this book and can't wait for it to arrive:

I love the PragProg team and I think this will be another great resource for me.

Monday, August 22, 2011

Css, page design and Rails applications

I think a lot about function and form when I'm coding. I hate looking at the default black text on white body when working on an application, so I usually do some basic styling early in development. I definitely tend to get bogged down with CSS, spending entirely too much time adjusting margins, padding and other granular details, but I don't think styling can be entirely separated from the function of an application.

For example, I created a basic navigation partial, wrapped it in a div and styled it to appear at the top of all the pages in my Manticore app. I'm not sure how this will change in the final version, or if I'll keep it at all, but it certainly helps out right now, when I want to quickly switch back and forth to test navigation or to see how a change in the code works. Or if it works at all!

How do you work with styling when developing a new application? Do you leave it until the end, or do you do some basic styling and then polish it up later? Do you have someone else do it? I know it doesn't make sense to style something that may not be included in the final version of an application, but I'm not sure how other developers work when it comes to basic styling.

Agile Web Development with Rails did styling early on in the development, with some minor tweaks here and there later. It was coming from the perspective of working for a client who wanted an e-commerce site created, so that may have had something to do with getting page styles hammered out early.

Tuesday, August 16, 2011

Validation errors in Rails

Whoa! I've been chugging along with Manticore the last 5 days or so and making some good progress. However, I've hit another wall (can you believe it?)

Basically here's the problem. I have a model Ac that creates Armor information for a Character. I've created some methods to calculate various data from fields from a Character's Ac model, and to avoid any errors when doing these calculations I need to validate presence_of and numericality_of several fields.

So my problem is two-fold. First off, when creating the Ac, all of the validation errors appear before the user has attempted to enter any data. Furthermore, the user can still create an Ac with no data at all. Clearly my validation isn't working.

Here's the code itself from my Ac model:

class Ac < ActiveRecord::Base
belongs_to :character
validates_presence_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection validates_numericality_of :base_ac, :armor, :shield, :dex, :size, :natural, :misc, :deflection


And the code from my AcsController:

class AcsController < ApplicationController
def new
  @character = Character.find(params[:character_id])
  @ac = @character.create_ac(params[:ac])

def edit
  @character = Character.find(params[:character_id])
  @ac =

def create
  @character = Character.find(params[:character_id])
  @ac =[:ac])
  redirect_to character_path(@character), :notice => 'Armor Class was successfully created.'

def update
  @character = Character.find(params[:character_id])
  @ac =
  if @ac.update_attributes(params[:ac])
    redirect_to character_path(@character), :notice => 'Armor Class was successfully updated.'
    render :action => "edit"


I'm not sure what could be causing this problem. I've got similar validation for the Character model and it works fine. Any advice? The form_for a new Ac is rendered from a partial in the Character show page, but I'm not sure if that would have an effect on this.

Also, on a slightly tangential note, when rendering a form like this, is that what's meant by a "nested form" ? I've seen this term a few times while searching for a solution and I'm unclear as to what it means.

Here's a link to the project on Github:

Thursday, August 11, 2011

Adding two columns in a table with Rails

I figured out a way to calculate totals from two different columns in a table, but I'm having trouble extracting that logic and moving it out of my view. In this case, an Initiative's total is the sume of the Dexterity and Miscellaneous modifiers. Here's the code I've got so far:

Initiative Total:
<%= (@initiative.dex + @initiative.misc) %>

Pretty easy, right? But I'd like to just call this something like init_total and call it that way, but I'm not quite sure how to write that code. Also, does it matter if I throw a .to_s on the end of this? I noticed it displays the same either way, but I don't know if a .to_s is strictly required. I'm guessing since this information is already a string, converting it to a string is redundant.

Just a quick update. Feels good to be making daily progress on Manticore, especially since I spent a long time spinning my wheels.

Wednesday, August 10, 2011

Implementing new methods in Rails

I think it's important that every time (or nearly every time) I sit down to code that I try to do something I don't know how to do. I'm making good progress with using the code I've figured out and applying it to other similar things. For example, with my Manticore app I can use the same methods to create Items to also create Special Abilities and Spells.

But what I want is a way to sum totals from different columns in a table, then display that total in the view. I was messing around with the sum and count methods I found in the Rails API, but haven't quite gotten this figured out. The result is a pleasant headache, and that's what I'm going for. I can't just rest on what I know, I need to be stretching my boundaries when I code.

I think the end result will be I'll learn new things faster and be able to work around road blocks more quickly when they DO arise. My ultimate goal isn't simply to build this or that application; I want to understand how Rails applications work, how they go together and how they're built.

Also, I'm going to start blasting out my rails blog posts in Google+ in addition to Twitter, so if you're seeing this twice? Sorry about your luck!

Tuesday, August 9, 2011

If and Unless Methods in Rails

Sometimes shit just works.

Sometimes I sit down to code for an hour or two and everything I try either works right away, or is broken in such a way that the first fix I attempt works.

Today was one of those days! I had some minor successes straight off the bat, such as moving Delete methods into Edit methods, moving Edit methods into the Menu partial along with navigation and changing the Show method for Characters in the Index view to display instead of a generic 'Show'.

But here's the big triumph of the heart tonight.

You may recall in my last post I was talking about how in the menu partial I didn't want to display pages that didn't apply to all characters. I don't want a spell tab in the menu for a character that doesn't learn spells, for example. So I figured out a way to solve this problem, and the really beautiful thing is the solution was maybe two lines of code. Why did I think this would be such a big deal?

Here's what I had originally:

<%= link_to_unless_current 'Special Abilities', character_specials_path(@character) %>

Changing this code so the Special Abilities page only shows up if it's been created is easy enough:

<%= link_to_unless_current 'Special Abilities', character_specials_path(@character) if @character.specials.exists? %>

But then I run into a problem. With the previous code, it was simple enough to create a Special Ability, since you just clicked on the Special Ability link and the show page would render the form, allowing you to create a Special Ability, or edit a previous Special Ability. So obviously I need to land a link to create that page somewhere.

The Character show page seems a logical choice, since it will exist before a Special Ability will, and a Special Ability's existence will depend upon a Character's existence, right? So let's wire that up:

<%= link_to 'Create Special Abilities Page', character_specials_path(@character) unless @character.specials.exists? %>

Making pretty good use of those if and unless methods!

I know Rails programmers often talk about how they can't believe something is so easy to do with Rails, but shit, I can't believe this was so easy to do. And it feels good to make this much progress on my own, because I feel like a lot of the time I'm just asking for help. This is a pretty good indicator that I'm figuring out how things work, where things go and how to make Rails sing and dance for me.

Monday, August 8, 2011

Working on personal Rails projects

So I've made some pretty serious progress with Manticore. So far, here's what I've got:

The ability to create a new character, with several attributes includine statistics, hit points, armor information and so on.
The ability to create and destroy items that belong to said character.
The ability to create and destroy special abilities that belong to said character.

Not bad! I feel like I'm making some real progress here. Here's a few screen shots:

When I work on a Rails application (and especially when I work on one for myself) I like to keep a to-do list of features I want to implement. It feels GREAT to have a roadmap when working on any project, and Rails is no exception. Here's what I've got so far:

Add Skills - Every character will need skills, and I haven't started to tackle this yet because I'm not quite sure how to do it. I think simplest would be to make Skill a model with several defining attributes that belongs_to Character, with a has_many relationship. This would allow users to create skills as necessary, and not add Skills they either don't have or don't use. Actually, you know what? I just talked myself into doing it this way. BINGO!

Add Feats - Feats are going to be similar to Special Abilities, and I'm not sure if I want them to be in their own tab in the menu partial or lumped in with Special Abilities. I like the idea of keeping them separate, because some characters won't have Special Abilities, though most (if not all) characters will have Feats. I also don't want that menu partial to get too bulky.

Add Animal Companions / Spells - Here's another thing I want to do. As of right now, my menu partial displays the same things for all Characters (although some of these are just placeholder text) - Character | Items | Skills | Special Abilities | Spells - and it struck me the other day that I shouldn't be displaying these pages if the character doesn't have them yet. After all, a fighter doesn't learn spells or gain an animal companion, so why show them in the menu partial? So once I get some of these other relationships hammered out, I'll be looking for a way to add these, perhaps from the Character's view page, and have pages populate into the menu partial only if they've been created. Eventually I'll want the ability to drag and drop these to organize them by user preference, but let's not get too deep into the styling woods just yet.

And finally, I'll want to clean up the actual code I'm using. @unixmonkey showed me a way to get what I want done, but said it was messy and he was right. Still, it's more valuable to me right now to have code that works and not the most efficient code possible.

Remember when I said I find myself focusing more on my own projects than the tutorials and books I've been using? That still holds true.

Sunday, July 31, 2011

More Routing Issues in Rails

I've made some progress with Manticore this weekend, but I've hit another wall. Surprise!

Thanks to @unixmonkey and @jqr, I can now add, view and destroy items, linking to the items index page from a menu partial that is called from the character's show page. Success! However, I thought it might be handy to be able to edit items. And that's where my problem comes in. For a while, I was getting a routing error. Then I edited the code and now I'm getting this old chestnut again:

undefined method `item' for #<Character:0x103f0ce50>

What gives? I thought I'd gotten rid of this guy when I defined the character in the items controller.

Here's my edit method from the items controller:

  def edit
   @character = Character.find(params[:character_id])
   @item = @character.item

  def update
    @character = Character.find(params[:character_id])
    @item = @character.statistic
    if @item.update_attributes(params[:item])
      redirect_to character_items_path, :notice => 'Item was successfully updated.'
      render :action => "edit"

And here's how I'm calling it from the partial I created for creating and editing items:

<%= link_to 'Edit', edit_character_item_path(@character, item) %>

Any more tips? I'm pretty sure I'm just not writing this correctly. This code is based on what I've got for my other models (statistics, armor class, etc) but I wonder if it might be different based on a couple of things. For one thing, those other models have a has_one relationship with Character, while Items has a has_many. For another, the has_one models are all displayed in the Character show page, while Items is being created from the Items index page. Am I on the right track here? Any advice as to how to solve this issue?

On a less begging for help note, I've spent a good 5 hours working on Manticore this weekend. I notice when I'm working on a personal project and not a tutorial, I can focus for longer periods of time and I find the work more interesting. When doing a tutorial, I feel like it's a valuable use of my time but it's not an interesting use of my time. Does that make sense? Regardless, I absolutely lose track of time when working on my own projects, even if it's just repeatedly butting my head up against trying to get a goddamn edit method to work.

Saturday, July 30, 2011

Models, forms and view pages in Rails

I'm back to working on Manticore after a couple months away doing tutorials. I've made some progress this afternoon, but now I've run into a snag.

Here's what's going on: I have two models, Character and Item. I've created a form_for new Items that belong to a Character. The form works fine when displayed in the Character view, but what I want to do is move the form and Item listing out of the Character view and into the Index page of Item, so I can link to it from the Character view. I've got a _menu partial that I'll be using to display other views relating to Character, such as Skills, Spells, Items and so on. I'm not sure what the issue is, but simply transplanting the code as is gives me this error:

undefined method 'items' for nil:NilClass

Here's the exact code I'm using:

<h2>Add an item:</h2>

<%= form_for ([@character,]) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  <div class="field">
    <%= f.label :type %><br />
    <%= f.text_field :type %>
  <div class="field">
    <%= f.label :location %><br />
    <%= f.text_field :location %>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  <div class="actions">
    <%= f.submit %>
<% end %>

<% @character.items.each do |item| %>
    <td><%= %></td>
    <td><%= item.type %></td>
    <td><%= item.location %></td>
    <td><%= item.description %></td>
<% end %>

Like I said, this works just fine in the character/show page, but does not work when placed in item/index and linked to from my _menu partial. Any ideas?

Here's a link to my git repository:

Sunday, July 24, 2011

More Heroku Rails Deployment Issues

I've (partially) fixed my issues with deploying to Heroku. The solution was to specify rake version 0.8.7, as noted all over Stack Overflow for people who had the same error I was getting. I could have fixed this issue earlier, if I'd realized you deploy to Heroku from Git, not from your local machine. So I was updating my code, then trying to migrate the database on Heroku and I kept getting the same error because the code hadn't been changed on Git. Still, progress!

But I'm still having a problem. Take a look at the deployed version of my Depot application:

And here's a screenshot of how it looks on my machine:

Heroku is not displaying the product listing and I can't figure out why. The database information is stored in a seed file, so I thought a heroku rake db:seed command would populate the data and fix my issue, but no such luck. I've also noticed that the new action for my Product model throws an error on Heroku, but it works on my local version. Any ideas what's going on here?

Here's a link to my git repository for this application:

Saturday, July 23, 2011

Uninitialized Constant Rake::DSL and Heroku

I took @jqr's advice and signed up for Heroku this morning. Agile Web Development had me working on running a virtual name server with Apache and it was way too complicated for my tastes. Apparently coders who don't want to deal with server-side headaches are pretty common, hence Heroku!

But I've hit a snag. I get an uninitialized constant Rake::DSL error whenever I try to run a migration on Heroku. Here's the full error:

gozer /users/tylermoore/code/depot master$ heroku rake db:migrate
(in /app)
rake aborted!
uninitialized constant Rake::DSL
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2482:in `const_missing'
/app/Rakefile:6:in `'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `load'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `raw_load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2007:in `block in load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2006:in `load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:1991:in `run'
/usr/ruby1.9.2/bin/rake:31:in `


Apparently, this is a well-documented error, and I've dug through a ton of Stack Overflow and Google discussion threads, trying various solutions but no luck so far.

I've manually set my rake gem to version 0.8.7, updated my GemFile and pushed changes to Git, which works for a lot of people, but not for me. Still, I'm not discouraged. I'll figure this out eventually. Just thought I'd throw this up here in case someone has had this exact error and found another solution.

Thursday, July 21, 2011

Setting up a virtual Apache server

Holy shit, 10 days without a blog post? Fear not, I have been coding! Just not writing about coding.

So here's where I'm at now. I'm near the end of the practical section of Agile Web Development. The chapter I'm on now is about deployment and I'm having trouble setting up a virtual Apache server and actually getting Depot to deploy. Everything appears to be installed correctly, but I can't get everything tied together correctly.

How do I find my host name? I'll need to define it as in my Apache configuration file. I thought it would just be, or perhaps, but neither of those worked.

I also had trouble editing my hosts file. I'm able to open it through the terminal, but it won't allow me to make changes.

Still, this headache is a minor set back. I know it's something I need to learn, but for now I think learning more actual coding will be more useful to me. Any good recommendations for new books? I really liked Agile Web Development, so I might look into something else by the Pragmatic Programmers. Not sure if Advanced Rails Recipes would be beyond me or not.