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
  bar
end


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:

Add:
<%= 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
end


This way, I can simply call Initiative.total 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])
end


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])
end


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 = @character.skills.build
  @sorted_skills = @character.skills.find(:all, :order => :name)
end

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:

Chorenivore

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:

Manticore

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.