Joel Always one syllable

The ampersand & a killer Sass feature

28 Jun 2011

#

Earlier tonight Adam Stacoviak posted something on his blog about the killer feature that is the ampersand in the Sass CSS meta-language. Go read it immediately. Go. I’ll wait here.

So – to boil this down … the “&” tells sass to pull the entire parent selector into where you place this beautiful little ampersand. The perfect use case that allowed me to dip my toes into this was with something like psuedo selectors for anchor tags. Example:

Simple enough, right? Pretty awesome. As Adam noted in his blog post though, the & doesn’t belong solely at the beginning of your nested selector – you can tack it on at the end of that nested selector for further customization. Let’s say the example I have above needs a special edge-case for a particular page, or page state — like what if I’m logged in as an admin? Maybe our page(s) have a new “admin” class added to our body tag? We could go the route of adding something after our scss block specifying this edge case.

But why? Why bump this down below as almost an afterthought? Shouldn’t we have that grouped inside within the context of the anchor tag? We can do that with the magical ampersand:

Pay attention to where that ampersand is. “Pre-pend this body.admin right before all of the parent selectors in this nested group”.

Now. Here’s where I hope to stress just how money this is. Because it is.

Have you used Modernizr? What about the google web-font loader? At the very least you’ve used the trick from HTML5 Boilerplate to target versions of IE with some well-placed conditional comments? What do all of these have in common? They all dynamically, in one form or another, add classes to the root html class. In Modernizr’s case it tells you what features you can hook into within your CSS. In Google’s web-font loader it will update some classes in to tell us if and when our typefaces are loading or have loaded. This is where that ampersand has made things easier for me. A perfect real world example to consider is when I was working on starting to integrate Quicksand, a free font from FontSquirrel, with Google’s Web-font loader, into the very much in-progress Design*Sponge redesign. I fell into a trap where I ended up tacking selectors onto a tragically long list for two states of the font – NOT loaded, and loaded. Not familiar? Let me explain.

The element that needed styling to use Quicksand was always set to visibility: hidden. Once the font(s) finished loading the html would end up with the .wf-active class, allowing us to then show the font(s) with visibility: visible. This is all to combat FOUT (“flash of unstyled text”). The tragedy was how I chose to tackle this at first – I had that previously mentioned LONG list of selectors, comma separated, that kept getting new elements whenever a new piece of text needed “QuicksandLight”. Poor decision. That CSS got unruly and terribly difficult to manage. I had sass partials containing beautifully compartmentalized and scoped selectors …

no, it's not okay

… and then this giant blob of garbage saying “these are hidden” … “until they get .wf-active” in the html tag.

Not ok. This needed to be dealt with. These edge-cases needed to show up right after the “normal” base selectors, not in a disparate location somewhere else in the CSS. I determined that the best solution would be to wrap these fonts and the associated states in mixins that could be used across our scss files. Here’s what I came up with:

At first glance it doesn’t look like such a big deal, but when you consider there are hundreds of elements on the site getting this font-face applied to it, it ends up turning into a chore mostly consisting of a lot of copy and paste. Really study that gist – when that clicked, it was magic.

As a bonus, consider this – originally I didn’t realize I needed to target IE as I did in the final resulting mixin. The site launched without .msie.wf-loading and .msie.wf-inactive in there. Without that treatment the fonts were not showing up in IE7 and IE8. Terrible. After a little research I ended up adding those two into the mixin and all was good in the world. No global search. No copy and paste needed. Run into that problem without using something like Sass, just plain vanilla css, and tell me you’re not annoyed. I promise you – you’re annoyed.

That’s but one example using the Google font-loader. Using this in conjunction with the conditionally set IE-related classes, or a CSS3 feature like “borderimage” (which I used the hell out of for DesignSponge), has been a god-send. Keeping everything tidy inside the scope of our nested selectors keeps things manageable and easy to find. There’s no need to go searching for similar selectors across your CSS file – because it’s right *there, right next to your normal, base selector.

Slides available from Railsconf 2011

17 May 2011

#

Get a look fast – I have a feeling some of these might not exist at these URL’s for all that long (especially the PDF’s)

Visualizing the difference between references_many and embeds_many in mongoid.

23 Oct 2010

#

This one gave me fits for a little bit not too long ago, and crept up on the mongoid list the other day.

One of the greatest things about mongo in what it does is the idea of embedding documents into other documents – at times removing the need for relations where it makes sense. The classic example being Blog posts and comments within that post. Why not just shove the comments directly inside of the blog posts’ documents? It’s faster and makes sense – these are just documents right? So let’s treat them as such.

But on occasion the need for relations remains. On a toy app I’ve begun rewriting to use Rails3 and Mongo (Mongoid, specifically) I ran into a conceptual road-block that I’ve seen creep up on occasion between the other (relative) newbies like myself – how the relations are stored between Mongoid objects. I needed a relational association instead of just embedding (why? the size limit for collections probably would have bitten me in the ass in the future). But after following the conventions in the documentation and inspecting how things ended up in the database I realized I had a few things twisted.

I think part of it, at least for me, is the idea of embedding gets in the way of how you perceive this getting stored within the mongo document(s). Take the example at the mongoid documentation under “Relational Associations”

class Person
  include Mongoid::Document
  references_many :prescriptions
end
class Prescription
  include Mongoid::Document
  referenced_in :person
end

When I look at that – I think that the Person would collect the references to Prescription, perhaps in a :prescriptions array. Such is not the case. Instead the Prescription objects contain a single reference to its “parent” object – Person. Below is a comparison of what you might think, versus how it’s actually stored in the database

john = Person.create
prescription = Prescription.create
john.prescriptions 
# {
# 	"_id" : ObjectId("4cc2f0bac0b37e9c17000001"),
# 	"_type" : "Person",
#	"prescriptions" : [ ObjectId("4cc2f0bac0b37e9c17000002") ]
# 	"created_at" : "Sat Oct 23 2010 10:27:06 GMT-0400 (EDT)"
# }
# prescription =>
# {
# 	"_id" : ObjectId("4cc2f0bac0b37e9c17000002"),
# 	"_type" : "Prescription",
# 	"created_at" : "Sat Oct 23 2010 10:27:06 GMT-0400 (EDT)"
# }

Versus what this is actually doing

# john =>
# {
# 	"_id" : ObjectId("4cc2f0bac0b37e9c17000001"),
# 	"_type" : "Person",
# 	"created_at" : "Sat Oct 23 2010 10:27:06 GMT-0400 (EDT)"
# }
#
# prescription =>
# {
# 	"_id" : ObjectId("4cc2f0bac0b37e9c17000002"),
# 	"_type" : "Prescription",
# 	"created_at" : "Sat Oct 23 2010 10:27:06 GMT-0400 (EDT)",
# 	"person_id" : ObjectId("4cc2f0bac0b37e9c17000001")
# }

I realize this follows the same old ActiveRecord conventions of the parent ID being stored in the children objects, but when you develop that big ole’ crush on, and get married to, the idea of mongo’s embedded documents – it’s difficult to switch gears!

If any information is misrepresented or factually incorrect please leave a comment and let me know!

Rack::Tidy and Devise in the Rack Middleware Stack

25 Sep 2010

#

After quite a bit of digging around, and a little help from mr. Jose Valim at Plataformatec, I realized that the combination of the Devise authentication gem, along with Rack-Tidy, aren’t quite so friendly with each other. The main culprit here, I would say is the Tidy gem. Why? Because the essence of its existence is to re-arrange the markup handed back from the app-server. So some things get lost in the shuffle during all that house-cleaning (please, correct me if I’m wrong).

I had a hunch that with a little musical chairs in the middleware stack, we could find a solution that would allow all pieces to live harmoniously. Luckily, I was right. The trick is to make sure Tidy is inserted into the stack before ActionDispatch::Flash (because Rack::Tidy was killing the flash messages returned from Devise/Warden) and before Warden::Manager (the rack authentication layer beneath Devise). The resulting stack, for me, looks like so (important bits in bold):

use ActionDispatch::Static use Rack::Lock use ActiveSupport::Cache::Strategy::LocalCache use Rack::Runtime use Rails::Rack::Logger use ActionDispatch::ShowExceptions use ActionDispatch::RemoteIp use Rack::Sendfile use ActionDispatch::Callbacks use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::ParamsParser use Rack::MethodOverride use ActionDispatch::Head use ActionDispatch::BestStandardsSupport use Rack::Tidy use ActionDispatch::Flash use Warden::Manager use Sass::Plugin::Rack run MyApp::Application.routes

And is accomplished with this code instead the app initialization process (application.rb):

config.middleware.delete ActionDispatch::Flash # remove from current position config.middleware.insert_before Warden::Manager, ActionDispatch::Flash # add it right back in before Warden config.middleware.insert_before ActionDispatch::Flash, Rack::Tidy, 'indent-spaces' => 2 # finally, add in Rack:Tidy before ActionDispatch::Flash.

The resulting stack looks like it’s working quite well for now.

Debugging in Cucumber

17 Jul 2010

#

As a relative newb’ to cucumber I realize there’s a lot to get caught up on. The one thing I do know is that there’s a lot that I don’t know. Having said that, when I run into a barrier or an issue and I want to dig into the source to figure things out, what do you do?

You break out ruby-debug, of course.

Add require ‘ruby-debug’ to features/support/env.rb and throw a breakpoint into your step definitions.

That’s all well and good, and it works just fine. But what do you look for while you’re in there? I spent the better part of an evening looking for how I could sniff around the html source cucumber was testing against and couldn’t find it. Lots of searching for how to pear into @response and @request – which end up being nil as far as I can see.

I had no idea.

Until I read this post from the LoED on how to test your source’s validity. In there was the answer:

page.body

Eureka!

Baby steps. I’ll figure this all out yet.

rvm, ree, nginx and phusion passenger

12 Mar 2010

#

A production web / application server that I maintain has been around for mostly wordpress and static sites we host for some of our clients. Soon, however, the need for some Rails-based client sites will be popping up for us over there. Traditionally the set-up for those apps have been in clients’ own hosting environments, or were apps I hosted in a dedicated app-server slice of my own. So, the need crept up, and now I’m left planning for now, and the future. And what is that future, you might ask (ok, probably not)? Rails 3, of course.

The baseline reference implementation for Rails 3, as I know it, is 1.8.7, but has been tested to work with Ruby 1.9, and also functions properly with Phusion’s Ruby Enterprise Edition (henceforth known as REE). To say that Ruby is in a transition phase is an understatement. The community has been hard at work trying to get gems, frameworks, their associated plugins, etc, to work with all of the new shiny ruby-based toys. In order to accurately test, the RVM project has stepped up as the solution for testing and developing across multiple Ruby interpreters.

New server setup, quickly moving innovation, growth and change … all of these point me in one direction – drinking the RVM kool-aid and getting right into it. But not without a few hiccups. Here are my steps in getting things rolling with rvm, nginx, ree and passenger.

Note: Don’t install nginx at first thinking that passenger will end up being installed as a plugin, or module. I wasted some time in doing that. When you go through the process of installing passenger it’ll ask to compile and re-install nginx. So we’ll get to that eventually.

To get everything compiling as I wanted I had to install a handful of obvious, and not-so-obvious, packages and libraries. To wit:

sudo apt-get install ruby-full build-essential curl libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev libgcrypt11 libgcrypt11-dev bison libreadline5-dev

Your mileage may vary.

Also, the irony doesn’t escape me that we needed to install ruby, “ruby-full”, in order to install a bunch of other rubies. But hey, whatever.

Install rvm. It’s as easy as following the instructions at the RVM site. I chose to go the gem route. Follow the instructions as are given and things will be fine. The only hiccups I had involved some libraries that are taken care of in the above package installs.

Install the versions of ruby you’d like. rvm install 1.8.6,1.8.7-head,ree,1.9.1

According to fellow boston.rb’ist @techiferous we use 1.8.7-head, because

# Rails 3 needs Ruby 1.8.7. Use rvm to manage Ruby versions. Do “rvm ruby-1.8.7-head” NOT ruby-1.8.7-p249 (broken gems).

After some time compiling and wrangling everything together you should have a handful of different rubies at your disposal. Please visit the rvm site for examples, use cases and general information. It’s worth your time.

At this point I switched to ruby-ree in preparation of the passenger and nginx install. rvm ree. A quick ruby –version now tells us that we’re running ruby 1.8.7 (2009-12-24 patchlevel 248) [x86_64-linux], MBARI 0×6770, Ruby Enterprise Edition 2010.01.

Install Passenger and Nginx. gem install passenger && rvmsudo passenger-install-nginx-module will get you started. Here’s where the install of Nginx goes down, as noted in the text after you run the command:

Nginx doesn’t support loadable modules such as some other web servers do,
so in order to install Nginx with Passenger support, it must be recompiled.

I chose to customize my own install and selected the second option. Do whatever you’re most comfortable with. I prefer to have my compiled source in /opt/local, but again, it’s all a matter of preference. After some more compiling, we were all done and have a newly compiled install of Nginx, with Passenger, Utilizing the REE ruby interpreter.

Last but not least, go thank Wayne Seguin for the work on RVM. Amazing work!

From the Ruby Noob Dept: Issue(s) with accepts_nested_attributes_for

27 Feb 2010

Finally took some time to jump in and refactor some nested forms at Thredded using Rails 2.3′s accepts_nested_attributes_for. Thanks to Ryan Bates’ screencasts on the topic it was fairly easy. A little code cleanup and everything worked as it should … other than one thing.

Can’t mass-assign these protected attributes

Noticed that error in my development logfiles after a particular form wasn’t being saved. A User class had some protected, and some not, attributes and until I added the Profile attributes to it, the nested form submitting a User and it’s associated Profile record would not save.

class User < ActiveRecord::Base
  has_one  :profile
  accepts_nested_attributes_for :profile
  attr_accessible :login, :email, :password, :password_confirmation
  # ...
end

Needed just the Profile attributes set as accessible and ready for mass assignment

class User < ActiveRecord::Base
  has_one  :profile
  accepts_nested_attributes_for :profile
  attr_accessible :login, :email, :password, :password_confirmation, :profile_attributes
  # ...
end

Another case where you need to know at all times where and if properties of your classes are locked down or not.

Sassy-pants

25 Feb 2010

I’m pretty set in my ways professionally these days, so it’s hard sometimes to make a shift from what I’m comfortable with to a methodology that’s contrary to something that still works.

Like CSS – what the what needs to change in my work-flow regarding CSS at this point? I’m more than comfortable with box-models, browser hacks, sprites, peek-a-boo and double-float margin bugs. Waking up one day and thinking – “I could be better” was the kick in the pants to try something new. Enter Sass.

Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.

I won’t go into the syntactic sugar that makes Sass so much fun – John Long [1] [2] and Adam Darowski have already done excellent jobs rounding up the high, and lower, level concepts and tricks. I highly recommend visiting and bookmarking those links for future reference.

A few things I’ve bumped into, however, that bear mentioning here involve a few tools and code snippets that I went looking for as I went down that sassy path. The first being a Textmate bundle for sass I found to help out during rapid and uninterrupted development. The syntax highlights are, of course, fantastic, but the killer feature is easily the quick CSS generation keyboard shortcut. Command-R will parse and generate your CSS file right there from inside Textmate. If there are any issues a tool-tip will pop up with the error. If you switch over and reload your browser too fast to see the tool-tip you’ll see an unstyled page – a big honking notice that you were doin’ it wrong.

The few bits of code, of many, that I needed to find, or create, quickly before getting down to business – Eric Meyer’s reset stylesheet, and maybe a mixin or two that I’m quick to use in a pinch – like .clearfix.

// Reset

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td
  :margin 0
  :padding 0
  :border 0
  :outline 0
  :font-size 100%
  :vertical-align baseline
  :background transparent

body
  :line-height 1

ol, ul
  :list-style none

blockquote, q
  :quotes none

// remember to define focus styles!
:focus
  :outline 0

ins
  :text-decoration none
// remember to highlight inserts somehow!

del
  :text-decoration line-through

table
  :border-collapse collapse
  :border-spacing 0

// ----------- Clearfix ---------------

.clearfix
  *display:                 inline-block
  &#038;:after
    content:                " "
    display:                block
    height:                 0
    clear:                  both
    visibility:             hidden

// ----------- Clearfix as mixin ---------------

=clearfix
  *display:                 inline-block
  &#038;:after
    content:                " "
    display:                block
    height:                 0
    clear:                  both
    visibility:             hidden

Those are two solid examples of how easy it is to just jump right in. So give it a shot – sudo gem install haml to install what you need, and get to work playing.

Tips for developing HTML emails

15 Jan 2010

#

Nested tables FTL
Option 1 – Don’t do it.

And if that’s not on the table (haha – get it?), I present to you …

Option 2 – With a few things in mind when you approach the assignment you’ll get through it. It might not be the most fun, but it’s all doable.

My first suggestion would be to take whatever time you estimated, and double it. Maybe triple it. If you’re reading this post in its entirety then I’m guessing it’s safe to assume these HTML emails aren’t a daily routine for you. If such is the case, the time it’ll take between your first tag, and the moment the email is spammed sent out will not be insignificant – 2-3 times the markup, 2-3 times the complexity in testing esoteric email clients. Your mileage may vary, depending on what the targeted visual design is. It’s always up to your discretion – but the one thing I didn’t anticipate, that I know is a rule, not an exception, is the time you spend on the testing process.

Before starting – these are the things you should have up front to make your life semi-easier.

  1. Create test accounts at gmail, hotmail, yahoo mail, and AOL. Except you can probably ignore AOL out of principle. I felt dirty just typing that. As with most things related to this practice – having to maintain test accounts at these email services is usually more trouble than it’s worth, but save yourself time and pain by using some sort of password database, such as 1password. Remembering passwords isn’t the hassle here – it’s the random usernames you’re going have to pull out of thin air, which you’ll end up using very infrequently. Trust me.
  2. An account at an email campaign website like CampaignMonitor or MailChimp. I’m a big fan of, and more prone to recommend, MailChimp not only for their pricing and offerings but the user experience throughout. It’s on my short list of sites that are actually fun to use – as silly as that may sound. Why Mailchimp? You can set up a sample campaign, point to your code on your webhost of choice, and send emails using the code hosted out there in the wild.
  3. A virtual machine with Windows, and the latest version of Office. This one’s a given as most emails sent for B2B purposes will end up in MS Outlook. As of right now the latest is Office 2007, whose changes to how html emails are rendered are the single reason to pack up and go home if you can. Want more info? Here you go. Office costs money, obviously, but if you don’t plan on doing too many of these html emails, there’s a free download at Microsoft’s that you can use as a trial for 90 days or so. Otherwise, purchase your copy legit … or find somewhere that will assist you in a … *cough* … longer “trial period“.
  4. If it’s in the budget – sign up for a screenshot generator. If you’re tasked with testing your table-bloated masterpiece in more obscure email clients – Lotus, or Lotus Notes – whatever it’s called. Outlook 2003. The aforementioned AOL. You might want to invest in an account at one of the screenshot generator testing sites like BrowserCam, Litmus or CampaignMonitor. Of those three I only plunked money down to try CampaignMonitor – which worked, but the screenshots were of varying quality. Some were half-generated. One looked like someone hit “ctrl-A” before the screenshot was taken. Very odd, but it did the trick to somewhat guess how things were looking. If I were to try any of those others instead I would probably go with Litmus. Again – ymmv.

The following are the gotchas and tips I’ve become familiar with recently through the course of developing a handful of these emails. These somewhat defy the logic you might be used to when developing for the regular web – a medium that’s already tricky and nuanced. Coding for email clients is downright dumb in comparison.

  1. Plan and internally conceptualize your tables. Lots and lots of tables, obviously. Look at the PSD handed off to you and, in your head, plan ahead of time how you’re going to tackle the layout. Don’t try and get cute with an overabundance of col and rowspans. It will only make things more difficult over time. I found myself starting with a main outer table shell consisting of a few rows and cells to get the content justified.
  2. Table cells that consist of just an image – make sure those images are all aligned left (or right, if you are so inclined). Some current generation browsers will leave a gap after the bottom of the image for some reason, regardless of white-space in your markup. Sure, might look great, but it will still jack up your already delicate table layout. So remember, aligning the image will fix this.
  3. Background images. Completely forget about them. They are dead to you. If you want this email to look flawless in Outlook 2007, there are no such thing as background images – either via inline CSS or the background property for TD’s. I hope you enjoy the slicing tool in Photoshop because you’re going to end up rather proficient in it by the time you’re done. Because of this I suggest you become friendly with whoever is designing the comp you’ll be developing. Possibly send them flowers or take them out to a nice lunch. Otherwise the possibility is quite real that you’ll receive a comp with copy floating all over and on top of arbitrary visual elements.
  4. On a similar note – familiarize yourself with what is supported in the various email clients. Campaign Monitor has put together a rather handy matrix of email clients versus the CSS that is and is not supported. Read through this as a primer and have it tucked away for future use – you’ll probably need it. Also at Campaign Monitor – a collection of free email templates you may download as reference, or possibly (if you bribe them), a basis for your designer to use as “inspiration”.
  5. Don’t expect an inline style at the outermost TD declaring the font information to cascade into your inner table soup. Somewhere in your code I suggest wrapping some comments around a collection of what you anticipate being a common set of inline style attributes. This will allow quick access to copy and paste into your ’s, ’s, ’s, etc.
  6. And finally – Comments. Be kind with your use of comments for the express purpose of landmarking where things are in your markup. Front-end development in 2010 is a beautiful thing and we forget how miserable it used to be 6 years ago. Over 25k in html alone is a hard thing to imagine these days, but when you get up to that you’ll thank yourself if you’ve placed gigantic honkin’ comments telling yourself where the left and right content starts and ends.

Final thoughts – You will no longer take for granted the wonder and beauty that is good, clean, lovely, semantic markup. It absolutely boggles the mind that corporate IT managers will fall over themselves getting new versions of Office rolled out to their IT infrastructure, but OMG A POX ON NEW VERSIONS OF INTERNET EXPLORER (OH THE HORROR!).

Last but not least – know where the closest liquor/booze/package store is. You’ll need a drink or two by the time this is over.

(hat tip to @bmenoza for the nudge in getting this post up)

Using Google Apps Email as Your App’s SMTP Server

27 Apr 2009 #email #gmail #google #rails #ruby #smtp

Something I’ve held out on for a while now has been to switch over the settings for ActionMailer in my application(s) to point to my hosted Google apps account.   I figured it was probably time to do so as piping email notifications through my comcast email account is generally, probably, a bad idea (courtesy of the “No Duh” department).

Seems like it should be rather easy, no?  Just change action mailer to resemble:

ActionMailer::Base.smtp_settings = {
  :address => "smtp.gmail.com",
  :port => 587,
  :domain => "hosteddomain.com",
  :authentication => :plain,
  :user_name => "account@hosteddomain.com",
  :password => "omgsup3rsecret"
}

Meh. Looks easy enough, right? Except for the fact Google’s got some magic TLS authentication thing going on – you’ll run into an error in your mailers resembling Must issue a STARTTLS command first.. Enough to make you work a little harder to get the magic working.

For those of you/us that are running Ruby 1.8.7 and Rails 2.3.x the answer is rather simple – add :enable_starttls_auto => true to your smtp settings, which will result in :

ActionMailer::Base.smtp_settings = {
  :enable_starttls_auto => true,
  :address => "smtp.gmail.com",
  :port => 587,
  :domain => "hosteddomain.com",
  :authentication => :plain,
  :user_name => "account@hosteddomain.com",
  :password => "omgsup3rsecret"
}

And for the rest of you/us (that would be me) that are still sticking with Ruby 1.8.6, there is an answer in the form of the action_mailer_tls gem. Following the readme will get you to right where you want to be – shoveling all the mail you would like into the ether that is the interwebs.

Meta descriptions and keywords for each page and post in WordPress

03 Apr 2009 #cms #meta #meta tags #wordpress #Work

After searching for a plugin that might accommodate this in WordPress and coming up empty, I went digging for a possible easy way to do this with the means available.   Logic dictates that with custom fields this should be rather easy to accomplish.

The only snag might have been that in retreiving a custom field for a page or a post you need the page or post’s ID.   Usually this id is readily available within “the loop”, but what about when we’re up in the tags?    A little searching in the codex reveals that we can grab your pages’ ID with $wp_query->post->ID.  Fantastic – because, with that we’re pretty much done! Adding the following in your theme’s header.php file between … :

” />
” />

.. and “meta_keywords” and “meta_description” as custom fields with your desired content for each will get you to where you want to be.

WordPress hosted on XO Communications.

27 Mar 2009 #hacks #hosting #plugins #wordpress #XO

Suffice it to say – it’s not a winning combination.   There are two definitive hacks you’ll need to get things to work.

First, a plugin to disable canonical URL redirection.  Second, a hack to wp-settings.php that circumvents the XO php configuration’s not having $_SERVER[‘REQUEST_URI’].

Update: the second hack will break the non-admin part of the site in the context of the current site I’ve been working on.  So your mileage may vary.

Installing libmemcached and the memcached gem on Leopard

16 Feb 2009 #development #gem #memcached #rails #ruby on rails #Work

face palm

What a huge pain in the ass.

I just spent hours trying to get every combination of these two to work together and nothing worked.   A handful of versions of libmemcached had no problems installing – .24, .25 and .26 were all easy to install, both from source and from macports.  However, getting the memcached gem to install proved to be way way more difficult.I tried with a myriad of options – the most promising piece of information looked to be from this gentleman’s website – but also proved fruitless.The final solution, after a LOT of googling and clicking around the rubygem forums – this post at Evan Weaver’s blog.  The libmemcached-0.25.14.tar.gz and memcached-0.13.gem tarball and gem, respectively, installed easily without any problems.  After downloading all I had to run was:

tar -xzvf libmemcached-0.25.14.tar.gz
cd libmemcached-0.25.14
./configure && make && sudo make install
cd ..
sudo gem install memcached --no-rdoc --no-ri

Done. Finally.

Update: There seems to be a few issues with the gem I link to being installed correctly in Snow Leopard.  After spending too much time trying to figure out why the gem wouldn’t install, I installed the current memcached gem (from gemcutter) on a whim – and it compiled, and worked, without a problem instantly.   So, if you’re running Snow Leopard and looking to install the memcached gem, try out the latest version first.One caveat – I’m still using the memcached server I linked to above, version  0.25.14, still from Evan Weaver’s site

Difference between :collection and :member in Rails 2.0

11 Aug 2008 #development #enlightenment #rails #Work

#

In getting up to speed with the new bells and whistles in Rails 2.0s RESTful routing capabilities I ran into something that puzzled me.  Of the options for a resource defined among your routes there were two similar pieces that, for one reason or another, I could just not find a solid and bulletproof explanation for – :collection and :member.  The :member part of it I got pretty easily for some reason, because its description is inherent in its own name … “a member among the default restful actions”.  The :collection part?  Notsomuch.  After some digging in the Rails mailing list I ran into a great, and worthy, explanation for this knucklehead by a contributer named “deegee”:

For example, with map.resources :reviews, if you want to add a method ‘delete_all’ that deletes all reviews at once. You may want to call that with ‘/reviews/delete_all’ and method PUT (never use GET to delete something). This method is acting on all resources (a collection), so the route should be:

map.resources :reviews, :collection => { :delete_all => :put }

If you want to have a custom action acting on a specific resource, e.g. ‘/reviews/3/give_rating’, then your action is on a member and the route would be

map.resources :reviews, :member => { :give_rating => :put }

So that’s it! They’re the same other than :member working on a single resource, while :collection works on multiple.  DONE!

I’ve got an idea. I need a programmer. It’s easy!

16 Apr 2008 #business #development #entrepreneurship #Work

#

There’s a really great post at this blog about how the writer, a developer named Ethan, was approached by some acquaintances with regard to a big idea they needed help in implementing. The usual banter ensues, in which Ethan discusses the terms by which he expects to be compensated. Whether in equity or at an hourly rate of payment.

The response from his pitch-man?

Hey, so, we aren’t really prepared to pay. I mean there isn’t that much to it, it’s just a PHP website with a MySql database, I was hoping you could just throw it together as a favor. Oh well, thanks anyway

The rest of his post echoes pretty much exactly how I would feel in this situation. “There isn’t that much to it”. That line destroys me. To anyone that might ever make that assumption – take a moment to step back, and really think about what you’re saying. It blows my mind to think that there are people out there that are so quick to make the leap that “there isn’t much to” someone’s craft.

“Dear Mr. Architect – can you design this house for me for free? I mean, there isn’t much to it, it’s just a house with a foundation and some walls”.

On another semi-related note. If you’re looking for someone to jump in on an entrepreneurial venture – the challenge you should expect to be faced with is to find that one special, talented individual that might share the same passion as you on this particular topic. From my perspective – that’s the key. Passion. Unless it’s for pay, it’s hard for some to get truly amped to knock out the creative, or code, for your new project. I’ve tried the same approach – “Work with me on this! We’ll rule the world“. It’s too nebulous a proposition for most, unless they know they’re going to LOVE this thing you’re creating.

My conclusion – work my ass off for a little extra money to invest in the paid services of my friends to help me where the help is needed. I just can’t ever expect to get something knocked out of the park by someone who’s going on my word – “This is going to be HUGE!”. If my name was short for something like … Joelstradamus … then maybe I’d be more eager to prognosticate on the magnitude of my many “next pet project”s.

WordPress 2.5 – I’m impressed

14 Apr 2008 #development #plugins #sara #wordpress

#

wordpress iconI’m in the process of building and theming the brand new bitbythebeautybug.com for Sara. Not only is she excited, but I’m elated to be working with the newest of the new in WordPress “technology”. It’s a strange leap from all the WP installs I’ve dealt with previously, but you can tell they’ve dropped a metric ton of work into making it the most secure (as it possibly can be) and usable blogging platform out there.

The first thing we did to get this ball rolling was to find a designer that truly “got” Sara’s vision for her brand. Luckily we were able to retain the services of a wonderful designer named Erika. I really liked the work she did for the RailsEnvy guys and figured I would give it a shot to see if she would be available for some design work. Turns out she had some space in her (I’m sure) busy calendar and whipped up some designs for us. Design – complete. Much thanks to Miss Greco!

On my end, the development work so far, other than slicing images, has consisted of a few tasks.

  1. Since this would be a custom theme, I looked for the most generic, baseline theme I could find to bend to my will. After a lot of looking I decided on one of these themes provided by Charity at Design Adaptations. It’s well developed, very well commented and absolutely gets out of the way of anyone who is using it as a jump-off for their custom wordpress theme. I’m still struggling with whether this is “custom” if it inherits code from someone else’s work. Regardless – she deserves kudos.
  2. One of the things I was looking forward to playing with in these recent versions of WordPress are the “Widgets” the WP team has put so much work into. Picking and choosing all of the content blocks you want to see around your site, re-ordering them as you wish – it’s just nice. See a widget you like, download, activate, put it where you want it. The only slightly difficult part was to enable the sidebar for widget support, and then figure out just how to enable multiple “sidebars”.
  3. Once the theme actually supported all of these widgets – it was time to find them.
    • Flexo Archives – reducing the clutter that the generic Archives widget spits out.
    • Limited Catlists – displaying the latest posts in Category X – for our purposes, the posts categorized under “Featured”. I couldn’t find a “Featured Posts” widget so this will just have to do.
    • Text widget – this one comes stock with WP by default and takes care of those scenarios where a little duct tape is needed. No decent FeedBurner widget? That’s fine – copy and paste the code Feedburner gives you into the text widget. Need a small “About” widget? Text widget to the rescue.

It goes without saying – I’m far from finished, but in the initial sprint to build out this site these are the pieces I managed to take note of. All in all though, WordPress 2.5 has been nothing short of a revelation in terms of where it came from, and where it’s going to. Huge props go to Happy Cog for the work they put into the new WP dashboard. It just feels so right.

Link Slugs with Javascript

26 Feb 2008 #javascript #rails #ruby #seo

Over at Thredded I am still using Rails 1.2.3 (I’m a little gun-shy to upgrade to 2.0) and, of course, felt that slugged links were necessary for both search engine optimization and making things like assessing site analytics a little easier. It doesn’t even need justification as it’s a matter of fact and necessity for any and all social platforms – blogging, forums, etc. With RoR 1.2.3 the best way to get your links slugging it out was to incorporate a plugin like acts_as_sluggable. It works like a charm, really, and I’ve never had any case where I needed extra functionality.

… Until now. I’ve started incorporating some auto-updating magic to Thredded and needed to grab a lot of data back from an AJAX call (sorry Steve – XHR) in the form of JSON. All well and good so far. But, when new links needed to be built on the client side, I didn’t have my handy built-in Rails ActiveRecord overrides to spit out my new slugged-up link! What to do?!

I dug through the plugin source and found the function that built the url’s slug -

def make_slug(string)
      string.to_s.downcase.gsub(/[^a-z0-9] /, '-').gsub(/- $/, '').gsub(/^- $/, '')
end

… And thought the quickest solution was just to rewrite it as a simple JS function.

function slug(id, title)
{
      title = title.toLowerCase().replace(/[^a-z0-9] /g,'-').replace(/- $/g,'').replace(/^- $/g,'');
      return(id '-' title);
}