Things I learned the hard way XIVII

jQuery When the DOM isn't reacting to your javascript selectors as expected try a little specificity: instead of this:
  $("#item_id > a")
do this:
  $("#item_id > ul > li > a'")

Posted by jeremy Sun, 14 Feb 2010 23:41:00 GMT


Javascript Exceptions - testing for true - When is undefined actually undefined?

Javascript has to know what 'it' is before Javascript can tell if 'it' is what you want 'it' to be. Example:
if (unreferencedVariableName) { alert('Impossible! an unreferenced variable cannot return true. In fact it cannot return at all!'); }
Result: ReferenceError: unreferencedVariableName is not defined
/* is as true as the unescapable pain and suffering of being an alive human being  */
if (typeof(cowBoySuckMonkey) === 'undefined') { console.log('suck it!') }


/*   these are false - no if-fu for you!   */
if (typeof(cowBoySuckMonkeee) != 'undefined') { console.log('suck it again!') }
if (!typeof(cowBoySuckMonkeee)) { console.log('suck it for real!') }

/* 'undefined is something I guess - just not what I wanted to test against */
if (typeof(cowBoySuckMonke)) { console.log('suck it nut gobbler!') }

var cowboySuckMonkay = '';
if (typeof(cowboySuckMonkay) != 'undefined') { console.log('suck it empty string!') }
/* no joy */
if (typeof(cowboySuckMonkay)) { console.log('suck it empty string, part duex!') }

/* well, I guess an empty string is false - CaulkGobblin! */
if (cowboySuckMonkay) { console.log('suck it empty string, you still not true!') }

if (cowboySuckMonkay == '') { console.log('suck it empty string, now you true!') }
so much to remember…

Posted by jeremy Tue, 18 Aug 2009 22:06:00 GMT


stupid arguments

rspec controller specs: YourClass.should_receive(:find).with() really cares about argument order and does not accept a hash of values where the params[:key] is named like the key in the hash key => value so:
## controller code
def find_my_fucking_shit
  @my_class = MyClass.special_method_in_model(params[:shit], params[:not])
end

## controller spec
# This will fail and you will want to punch a bitch in the nose because you spent two fucking days 
# figuring you were just really goddamn stupid (which may be true) because it should work but it doesn't
it "should find shit" do
  MyClass.should_receive(:special_method_in_model).with({:shit => 'will', :not => 'work'}).and_return(mock_my_shit)
  get 'find_my_fucking_shit',  :shit => 'will', :not => 'work'
end


# This will pass
it "should find shit" do
  MyClass.should_receive(:special_method_in_model).with('will', 'work').and_return(mock_my_shit)
  get 'find_my_fucking_shit',  :shit => 'will', :not => 'work'
end
Yes, I know about hash_including(). For some reason it failed because ":action => '_controller_action_', :only_path => true" was being included in the with() arguments hash and it made the should_receive fail - even though hash_including is supposed to deal with this. It may be a rspec_rails thing. I have not dug into the rspec code very deep to see what I was doing wrong or if it's a bug or if the universe just hates me.

Posted by jeremy Thu, 22 Jan 2009 06:44:00 GMT


rspec/cucumber/webrat - remember this shit

In a feature file you CANNOT comment out text on the end of a line - it will say your shit isn't implemented.

'test.local' is the URL rspec uses when running specs for controllers - so 'test.local' is the URL webrat/cucumber uses. Making possible testing of subdomain handling.

Single quotes are treated differently than double quotes - have no fucking idea why

Sometimes running features works - sometimes not. Putting the following in features/support/env.rb helped when some steps would pass when others wouldn't:

#Seed the DB
Fixtures.reset_cache  
fixtures_folder = File.join(RAILS_ROOT, 'spec', 'fixtures')
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
Fixtures.create_fixtures(fixtures_folder, fixtures)

This will ONLY work if I have fixtures defined for my models. I need to get with the automated fixture hipsters.

Posted by jeremy Sun, 18 Jan 2009 08:58:00 GMT


things i had to do to make mephisto 0.8.1 (kinda) work with rails 2.2.2

replace in config/environment.rb:

config.gem 'will_paginate', :version => '>= 2.2.2'
with this:
config.gem 'mislav-will_paginate', :version => '>= 2.3.2', :lib => 'will_paginate', :source => 'http://gems.github.com'

comment out in config/environment.rb:

config.gem 'tzinfo', :version => '>= 0.3.12'

I had to add:

require 'liquid'
require 'will_paginate'
to config/initializers/mephisto_init.rb

change line 17 in the index action in app/controllers/admin/articles_controller.rb to this:

    @articles = Article.paginate :page => params[:page], :per_page => params[:per_page], :conditions => ['site_id = ?', site.id], :order => 'contents.published_at DESC', :select => 'contents.*'

remove tzinfo from vendor/gems/

commented out erb tags on line 32 and 37 of app/views/admin/settings/index.html.erb.

32     <dd><%#= time_zone_select 'site', 'timezone_name', TZInfo::Timezone.all.sort, :model => TZInfo::Timezone %></dd>
33     <dt>
34       <label for="site_lang">Site language</label>
35       <span class="hint">Used to specify language in your site feeds</span>
36     </dt>
37     <dd><%#= f.text_field :lang %></dd>
Now I can't set the timezone or language of my rss feed until I figure out how to get the rails version of TZInfo::Timezone to not give me a NoMethodError

Posted by jeremy Fri, 09 Jan 2009 09:52:00 GMT


rails rjs - things i learned the hard way | xi

too many div’s and things go POOF!

When you have a styled div set with an id inside another div on safari at least. I’m going to explore this further, but it seems at this point I’m stacking my nodes too deep, MEANING if a styled div is inside another div that is replaced by an rjs template which has a visual effect to appear the styled stuff inside the div inside the one affected by the javascript response will remain hidden while all the stuff around it will pop into view. Selecting on the screen around the blank areas will reveal the content. Use span’s or class declarations to avoid the same 4 hours of frustration I just had. Of course this could all be wrong and I’m foolishly pointing west when the true way is north. In any case it wasn’t working as expected and now it is so I am of the mind that I solved my problem, be it maybe for only a moment.

remember to float the containers holding the floats

And clear your floats. Boxes are a pain. Tables are ugly. Love thy stacked attributes.

That is all.

Posted by jeremy Mon, 10 Apr 2006 23:28:00 GMT


on the process of progress

Essential understanding: In php str_replace and preg_replace do function similarly yet if you want exact matches you have to specify your regexp pattern with serious prejudice lest you match ANY and ALL partial or exact string matches and fubar your sweet logic with redundant nasties. I consider knowing this progress. Next up is understanding the hows and whys of stringing methods in ruby... Feet don't fail me now!

Posted by jeremy Fri, 10 Mar 2006 18:11:00 GMT


things i learned the hard way | VI

Error handling in rails is very technical. The TextMate Backtracer Plugin has been invaluable to me in my development in recent days, yet it only gets me to the file(s) when something is amiss in the code.

Building and running tests is one way of confirming the functionality of your application, and I’m learning the power of good testing, be it quite slowly and with a lot of errors.I’ll get there.

Here is a short list of things I had to consider when flopping from code to browser during development and things kept blowing up in my face:

  • Ruby/Rails has RESERVED WORDS. If you have a class/table that isn’t playing nice make sure you aren’t naming it with one of these. This is tantamount to pouring sugar in your gas tank. And then driving in reverse at full speed. While wearing a blindfold. With your hair on fire.
  • Column names in your tables need to change with alterations to any class/model names, as well as any has_many/belongs_to associations along with any model inclusions in your controllers. If you’re not to invested in the code it’d probably be easier to regenerate a fresh app with the correct model/controller name. Running ./script/destroy (the arch nemesis of ./script/generate) can help in crime scene clean up, but you still have all those pesky symbols/variables/methods with the poison name throughout your app patiently waiting to spurt their demonic ire. Exterminate them with aggression.
  • An objects information will carry from request to request in the session but you still have to stuff it into an instance variable inside whatever controller method is being called upon. I have a tingling sensation in my unmentionables that suggests session customization and databases can smooth out this bumpy road, but this strains the withering tethers of my sanity upon contemplation. I can only learn so much each day.
  • Getting compile errors means you’re trying to bake a duck with a hammer on a string in a pail of kittens. It won’t work. Ruby/Rails doesn’t know or particularly care what you are trying to do, but how you are going about doing whatever it is you are trying to do will never, ever work no matter what. Get rid of whatever you added since the last time it worked and try again. Remember when you went to grandmas house and you had to take off your shoes and you weren’t supposed to go out into the field because you’d get muddy? Yeah, Rails has grandma rules that sometimes take all the fun out of life and make your feet cold.

Throwing away code is a part of development, just as throwing away designs is a part of being a designer. Having the willingness to let go of what’s not working makes room for what will. Even if what that is is nowhere to be seen at the moment.

Posted by jeremy Fri, 24 Feb 2006 17:29:00 GMT


things i learned the hard way | V.

First things first. When you make models and then relate them to each other using :belongs_to and :has_many you automagically add a _*method*_ that is the name of your class in your model to all of the other models it has a relationship with. Yes, I know this is 1A Rails stuff but I don't learn as fast as you big brains out there. I started on this journey in 1996 making label tags to stick on furniture for presidents day sales with one ink color while an angry marketing director denounced my lack of moxie. It's a long way from learning how to use the pen tool in illustrator 5 to here. Now that things are really weird here's some code:
@project = Project.find(params[:id])
@hours = @project.hours.find(:all)
I have a *Project* model and an *Hour* model. I have a _projects_ table and a _hours_ table in my database. I use:
has_many :hours
in my project model and:
belongs_to :project
in my hour model. This is why I can apply the _hours_ method to my @project array of objects. ActiveRecord does the hard stuff. Now I wanted to get the total of all the hours for a project. But how to do this? At first I tried looping and trying to add each hours_billed to the next one in the array but I kept getting a fixnum error, or being told that it can't write string to whatever. Yeah, I'm a big dumb monkey hoping to be the one in a million to randomly reproduce the works of shakespeare by banging on my powerbook while shrieking and flinging my poo. I eventually opened my picaxe and found something called *inject*. This looked promising. But I, in my unique way, visualized my @project array as needing to be fiddled with to extract the column I wanted and get the value that was inside of it. I tried:
@total = @hours.billed_hours.inject(0) {|sum, element| sum + element}
Thinking this is how it should work. I mean when you loop through your instance variables in your views you access the attributes of your object by putting _object.your_column_ so I thought this was the way to do it.

*_WRONG!*_

I kept getting a noMethodError because there was no method called *billed_hours* in my model. WTF? After I inquired at the irc room #rubyonrails about how to do something like this I was directed back to the *inject* method, except this time I got the little nugget of enlightenment I so desperately needed. Check it out:
@total = @hours.inject(0) {|sum, element| sum + element.billed_hours}
Holy shit! It worked!. I was trying to force it before it was ready (that's what she said) and all I needed to do was understand how you use the *inject* method to iterate through a collection of objects. My assumption of needing to extract the attribute before the block was wrong _wrong_ _*wrong*_! You feed your collection of arrays into the block AND THEN call the attribute you want from each array inside of the block statement and as it evaluates each array that passes through your magic walking fingers machine it will add the stuff you tell it to and when it gets done you have a total. I plan on extrapolating this knowledge into more understanding and eventually prettier code. I'm always getting ahead of myself, and this was just one in a lifelong string of examples. The pragprog books use encouraging, accessible language to explain and educate someone who is using their materials to learn Ruby and Ruby on Rails. I know the words are giving me the information I need. The problem comes when my internal parser bends the words into a funhouse mirror reflection of their literal meaning and then I find myself feeling like I'm 2 steps behind and I missed the base abstractions that everyone else just knows because why wouldn't you know that, stupid? I'm fighting 3 battles at once with this stuff. I'm fighting the learning disability with language, the attention deficit disorder, and the peculiar emotional twists that can result from 30 years of living with the first two. I think in dependencies and relationships. Everything has a cause and effect. I've always understood that information is constant, it is just it's form that changes. The major hurdle has been translating the syntax into jeremy-speak and converting external information to internal understanding while avoiding the frustration and despair these activities can produce. So now I know you can get at the attributes of your object (the columns in your rows) inside the block that the inject method expects as an argument. Next.

Posted by jeremy Sat, 21 Jan 2006 17:32:00 GMT


learned the hard way | I.

Ceaseless curiosity and always taking 3 lefts to go right. Some things gleamed recently:
  • USE ‘apachectl’ NOT ‘httpd’ to stop apache1.3 and release the port. THEN ’ sudo /opt/local/apache2/bin/apachectl -f /opt/local/apache2/conf/httpd.conf -k start ’ to get apache2 running. Specifying the full paths is how you tell apache2 it’s their turn to bat.
  • apache2’s http.conf default took two days of my life away. Comment out the unique ID module line and blues skies will you see.
  • to use new config use the command above, but replace ‘start’ with ‘graceful’
  • alias and directory settings are a bitch.
Just a few of the many things I’ve learned. This knowledge is basic, but I didn’t have it before. I was stuck. With enough ritalin and diet coke I was able to keep banging my head on the terminal until a curiously dull exclamation mark would appear above my head and I would make a simple and obvious change in my approach that is assumed knowledge everyone got two minutes after they were taught where the power button was on their machine but I never learned because I don’t play well with others or authority figures.

One interesting twist is that the big bad scary complex command line has been demystified. I kinda got it now. Now when something doesn’t work I have a 50% chance of knowing what question to ask and where to look to find out what I’m not doing correctly. Prior to this point in time I would’ve had a snowballs chance in hell of fixing something on the command line if I broke it. This is what an optimistic person would call progress.

I started as a graphic designer (layout monkey) and it’s been a long road of learning by necessity how to make stuff with html, css, php, mysql, javascript, and now ruby/rails. Still learning. Always have been. Always will be. It’s a bitch.

Posted by jeremy Sat, 19 Nov 2005 12:00:00 GMT