encontro cytotec bh harga ciprofloxacin generik tetracycline use in foals cialis at the best possible price metformin causes kidney problems what is in wellbutrin sr wellbutrin para tdah esomeprazole pbs japanese light switch viagra teeth clenching side effect zoloft foglio illustrativo zovirax labiale buying clomid on internet when a man uses viagra does it feel numb co trimoxazole double strength bactrim ds side effects of the drug flagyl cipro side effects headache metformin hydrochloride for pcos lisinopril hair loss men what cold medicine can i take while on lexapro pain in dogs while on prednisone buy generic albuterol sulfate canada ciprofloxacin hcl 500 mg and tylenol pm prednisone withdrawal effects treatment anti nausea drug zofran prednisone dosage for feline ibd viagra use with alcohol what is inderal used for anxiety skipping cialis one a day what is the normal dosage of doxycycline hyclate is tadalafil safe with hep c cialis 5mg cost in alberta diflucan confusion viagra sellers in sydney amoxicillin clear discharge therapeutic dose for neurontin cialis per chi non ha problemi will cipro help herpes vendo misoprostol iquique azithromycin 500 cost dublin viagra apoteka srbija generic safe tadalafil nederlands what time of day should i take my prednisone azathioprine prednisone nuvaring bactrim ds thyroxine cure lipitor blood sugar levels eye pain when using ciprodex otic is albuterol sulfate an antihistamine what if i accidentally take two allegra celebrex withdrawal singapore super x vega sildenafil 100 mg tamoxifen as treatment of gynecomastia clomiphene for women online canada prednisone 10mg for 10 days cialis per ?berweisung bestellen albuterol nebulizer .083 hcpcs amoxicillin and renal transplant viagra will at affect your reglar erection is allegra 120 safe during pregnancy acyclovir untuk herpes nolvadex 20 mg 60 tab price ondansetron class pregnancy lexapro benadryl interaction can levofloxacin be problem ejaculating while on viagra thin pcos metformin weight loss metronidazole to treat urinary tract infections propecia to buy cialis next day federal express does topiramate speed up your metabolism viagra keep hard on viagra 100mg google checkout uk rite aid terbinafine hcl 250 side effectos propranolol e sibutramina how much prednisone for 10 pound dog amoxil and sinus cough with gabapentin el ciprodex reacciona a el alcohol cialis viagra yorum topiramate and restless leg syndrome amoxicillin to treat uti on pregnancy prednisone lipitor interaction pediatric dose amoxicillin otitis media cymbalta helps with what what is a high dose of prednisone benefits of sertraline hcl levitra es peligroso liquid viagra paypal misoprostol eat where i can buy clomid in philippines aspergers celexa how long does metformin give you diarrhea clomid prices walgreens neurontin for body pain lek levitra cena metoprolol koude voeten atomoxetine urine sildenafil y el ramipril aliskiren amlodipine and hydrochlorothiazide neurontin tablets 300 mg tiempo de duracion de sildenafil traghetto da bari a cipro is tadalafil from india safe smoking while on metoprolol what does viagra do viagra side effects taking paxil can i take vitamins while on azithromycin common lipitor doses topamax 25mg cost clomid and progesterone levels pregnancy doxycycline rtta can i take celexa with tylenol pm levitra red bull can amoxicillin cause diarrhea in infants valtrex cancer treatment singulair y montelukast sildenafil und dapoxetine tablets does nolvadex cause cancer can i give my dog amoxicillin for people one time dose diflucan can you take flomax in the morning propranolol imitrex lyrica neurontin anxiety where to buy viagra in islamabad singulair junior 5mg kautabletten what will happen if i double dose my 10mg lisinopril why shouldn i drink while taking metronidazole nexium patent expiration adalat 9 december phenergan dosage for infants can lexapro make you nauseous cialis in zorgverzekering nederland ano de lan?amento do viagra celebrex long term usage t l phones sp cialis viagra cost tricare merknaam lipitor zofran diabetic gastroparesis is celebrex being taken off the market how do you know if your zoloft dose is too high adalat 12 february 2011 diflucan 150 prima o dopo pasti bactrim sciroppo bimbi lisinopril dose in chf can i take prednisone for a sinus infection does avodart hair loss taux normal de thyroxine safe dosage premarin cost of 10mg lipitor adderall xr and neurontin how do people get high off seroquel adalat oros ppt estrutura quimica misoprostol informa??es sobre cialis allegra knock off can you get high off 180mg strattera hold plavix prior surgery gabapentin and libido misoprostol for cervical softening glucophage administration back pain during ovulation on clomid nolvadex clomid libido augmentin probiotice how much does azithromycin cost without insurance allergie au celexa does ibuprofen interfere with cymbalta phaseolus vulgaris orlistat zofran solution for injection how long does it take for acyclovir to start working how long dose a erchen last with viagra azithromycin 1000 mg tablets vart kan man k?pa cialis metformin in chf nexium 20 mg 0800 pharmacodynamic action of hydrochlorothiazide baclofen causing myoclonus type of estrogen in premarin when does tendonitis from levaquin go away drug interactions singulair lowest dose of celexa can neurontin be taken once a day how to take cipro for traveler diarrhea neurontin 600 mg cipralexin kanssa will bactrim cure mrsa antidepressants on the market pros and cons of proscar nombres genericos cytotec fast acting viagra jel how do you pronounce azithromycin 5 htp and wellbutrin topamax e stanchezza viagra taken with alka seltzer synthroid with ibuprofen cialis 5 miligramas british pharmacy viagra zofran dose per kg allegra haljine slike terbinafine hcl tablets 250 mg cipro and flagyl effect on organs wie lange darf man viagra nehmen maxalt therapeutic class sertraline appetite loss hotel allegra berlin zithromax vials does cialis help with blood pressure loose pfizer viagra online zovirax waterpokken flagyl and nyquil doxycycline 100 mg uti inderal 40 cp does clomid cause impotence metformin miscarriage rates zovirax cream safe during pregnancy clomid 50mg ohss cialis croatia buying across counter azithromycin chancroid walmart propecia 1mg albuterol 4 mg side effects the levitra girl clomid ob?sit zyprexa olanzapina effetti collaterali dose of nifedipine for achalasia augmentin et urine bactrim to treat trichomonas viagra frequently asked questions cost of wellbutrin at costco doxycycline monohydrate for sinus infection bactrim 200 40 mg fiyati dentist gave me amoxicillin zoloft emagrece cost of generic olanzapine info om kamagra yeast infection does not respond to diflucan ondansetron lexi comp buy orlistat in uk ilosone gel ? bom can you take painkillers with metformin priapismo com viagra missing alcohol with cialis no lamisil nails will 10mg of cialis make me hard major depression cymbalta can amoxicillin be used for bladder infections side effects bupropion sr 100mg do men organism on viagra does amoxicillin flush out sperm from body misoprostol tablet price in india wellbutrin dosage for sad xenical causes liver damage levitra for sale in the philippines propecia price at kroger amoxicillin and body aches does ciprofloxacin have anaerobic coverage do seroquel side effects wear off wellbutrin sr and wellbutrin xl difference topamax 50 pre hotel cipro lido venezia side effects of metformin 1000 strattera oral amoxicillin for wisdom teeth pain seroquel prolong zwangsgedanken can i drink green tea with synthroid como identificar o cialis falso orlistat y consumo de alcohol do not take cialis while using nitrates bipolar medications zoloft khasiat obat novamox 500 amoxicillin seroquel age range jak stosowac fluconazole lisinopril 5 mg identification comparison claritin allegra zyrtec augmentin gyereknek order viagra online botswana exodus oxalato escitalopram 10 mg furosemide oral iv ci cipro 55 for sale doxycycline cost forum nizoral kutya knee injections contraindications clopidogrel allegra young duke weaning off 10mg prednisone gebelikte zovirax azithromycin los angeles levaquin for earache extenze compared with cialis kamagra forum uk where to buy nolvadex in canada forums how to counter cialis headache viagra initial purpose dissolution of atorvastatin tablet viagra tablets c200 in urdu language can you use viagra with a penile pump cialis is it harmful lamisil 250mg tablets price in pak rupee caremark prior authorization form for nexium cialis and pinapple legitimate viagra refractory period viagra sales in sydney will cialis make you bigger can paxil cause thyroid problems cialis prix en belgique metronidazole my dog does hydrochlorothiazide cause high blood pressure can you take ibprophin with viagra metoprolol pharmaceutical company thyroxine in metabolic rate cytotec and smoking cymbalta every two days reviews of pink viagra montelukast veterinary use how much is levitra on bcbsfl premarin lips airport dubai apotheke viagra probe kostenlos viagra viagra pay with mastercard lamisil crema cuanto cuesta amoxicillin and prostate infection is homemade cialis safe lamisil tablets directions pulse dosing can you sniff strattera amoxil high blood pressure difference in 50g viagra and 100g viagra webmd lexapro acyclovir treatment of herpes period after clomid use doxycycline to stop period azithromycin 250 mg tablet gre how long before cialis one a day kicks in quetiapine benzo withdrawal viagra consegna veloce symptoms of tetracycline overdose find viagra edinburgh sites posted cranberry pills and amoxicillin propranolol for rls doxycycline hyclate for dogs uk kamagra shop stuttgart azithromycin covers can prednisone cause shaking azithromycin thuocbietduoc viagra trouble de la vision safely weaning off cymbalta metronidazole presentation is it illegal to buy viagra from someone viagra legal im internet viagra 50m cialis products for sale levitra pro fast delivery fucking mature after viagra cuantas veces se puede usar cytotec how do i wean off celexa cymbalta message board what if i stop propecia viagra makes you come faster cialis good effect accidentally swallowed 2 lisinopril pills prednisone missed dose bactrim yaz can i take half a pill of levitra twice daily what color is cialis pill nizoral cream for yeast infection ciprofloxacin niosomes starting clomid 50mg can you get clomid over internet doxycycline acne instructions effectiveness of doxycycline for malaria allegra pillen what is the cost for one cialis pill caverjet better viagra ringworm and nizoral proviron vs tamoxifeno elevated bp on prednisone z pack prophylaxis and efficacy of doxycycline for syphilis prednisone uses rash obat ciproheptadine tablet paroxetine faim doxycycline in filariasis proscar permanent side effects cialis salts testosterone enanthate and nolvadex cycle onset time of lasix prospecto del seroquel valtrex and imitrex buy propecia 5mg australia bupropion sr bipolar disorder female viagra and viagra for men viagra pode nao funcionar cipro causing kidney pain metformin swelling ankles can i take mucinex while taking azithromycin simvastatin crestor lipitor wellbutrin in teenagers clomiphene citrate usage zyvoxam pfizer ventas mexico what not to take while taking azithromycin aaron levitra wiki allegra otc packaging celexa side effects sleeplessness doxycycline storage stability viagra generika berichte topiramate not sleeping levofloxacin for aprire una banca a cipro linezolid epocrates can i buy cialis at wal mart clomid apres ivg subcutaneous ondansetron h pylori treatment with levofloxacin neurontin drug interactions lexapro clomid pct for test cycle sildenafil causa dolor de cabeza lamisil at lotrimin af baclofen helps sleep propecia and natural body building xusal und singulair augmentin angine rouge propecia lifetime lexapro at night time using muse with cialis c diff ciprofloxacin mrsa antibiotics cipro china viagra girl fuck taking wellbutrin during third trimester can cialis make you go soft cymbalta withdrawal symptoms how long stesolid vs atarax guerra di cipro 1573 levaquin lawsuit settlement list of birth defects from paxil viagra shot ingredients metformin 500 mg novo chantix and wellbutrin combination levitra apotheke kaufen adalat 21st may 2011 can you take viagra into thailand azithromycin average dose erectile dysfunction lisinopril hctz viagra pressure present can you take amoxicillin with an antihistamine lexapro causing suicidal thoughts nolvadex 10 mg 30 tableta for men infertility augmentin ear infection baby what is the average settlement for a plavix lawsuit septra vs. cipro for prostatitis kennel cough doxycycline dokteronline zithromax premarin aumenta a libido lexapro a controlled substance lamisil tablets no pres azithromycin at cvs precio del adalat oros can doxycycline cause swollen glands zovirax attest feeling hyper on lexapro kamagra oral jelly headache cialis medication can furosemide cause dry mouth nexium appendicitis cymbalta iron interaction side effects of tetracycline in horses can alprostadil be used with viagra iets anders dan viagra cum more times with viagra when to start using ovulation tests after clomid iv versus oral furosemide celebrex sulfa interaction singulair farmacias guadalajara does celebrex increase heart rate penicillinallergi amoxicillin is cipro bad for the liver metronidazole benzoate oral viagra dla 25 latka can i order viagra overnight i accidentally took 2 metformin bupropion ila viagra hangi doz is 40mg of levitra safe topamax effect on serotonin what antibiotics are used for chlamydia and flagyl italia cipro low cost erythromycin bloated stomach best time of day for paxil levaquin questions nizoral shampoo safe vidalista vs cialis metformin ldh cialis.24 hr testosterone enanthate tamoxifen prednisone pregnancy low platelets how many milligrams should a male take of cialis metronidazole tablets over counter what does the 10 mg cialis look like buy female vaginal viagra pulmonary lymphoma vardenafil can taking clomid give a false positive pregnancy test lexapro vs generic which better how long before cialis becomes affective cipro makes my poop yellow metronidazole used for herpes in the mouth prednisone 12 day taper i premarin iv package insert code like water, compile like bamboo! — Glenn Fu

CORS + Heroku + Passenger + Cloudfront

I host Farmstand on Heroku, and I prefer to use Passenger to run it. I was using the asset_sync gem to connect my assets to Amazon S3 + Cloudfront, but recently the user-env-compile feature was removed and now it’s suggested that you have CloudFront pick up the assets directly from your server instead of sync’ing them there yourself.

This sounded like a reasonable thing until I realized that you can’t set an origin policy in this case. If you follow the suggested setup you’ll discover that CloudFront sets the headers exactly as it receives them from your app. That means if you want your CORS-happy headers on your fonts, your server must deliver them with those headers. Some people will point out that you can set default headers in Rails 4, but running curl -I was showing none of those headers, and just some information about Nginx. The reason was that for precompiled files, Nginx would see them, and serve them, and never even let the Rails server know that the request had happened, giving no opportunity to add the custom headers.

FireFox was showing me:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://d1bej2a8uvz4or.cloudfront.net/assets/ss-pika-02874436ebea92b029d8015ec170991f.woff. This can be fixed by moving the resource to the same domain or enabling CORS.

The issue was that the Nginx template provided by Passenger containing this:

location @static_asset {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header ETag "";

Recently, as in last month (March 17), Passenger added support for providing a custom template for Nginx in response to this very issue.

Now as long as you ensure your Passenger gem is >= 4.0.39, you can run
ls $(passenger-config about resourcesdir)/templates/standalone/config.erb
to see what the default template is, and make your own version. I put mine in ./config/config.erb, and then in my Procfile changed my web line to
web: bundle exec passenger start -p $PORT --max-pool-size 3 --nginx-config-template ./config/config.erb.

Now you can add the needed headers to that same section of the template to look like this:

location @static_asset {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header ETag "";
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Request-Method *;

In my staging.rb/production.rb file, I can use:

config.serve_static_assets = true
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'

To get a really close-to-actual test in my local environment, I ran:

RAILS_ENV=staging bundle exec rake assets:precompile
RAILS_ENV=staging foreman start web

and then:

$ curl -I
HTTP/1.1 200 OK
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Access-Control-Request-Method: *
Cache-Control: max-age=315360000
Cache-Control: public
Content-length: 22404
Content-Type: application/x-font-ttf
Date: Tue, 13 May 2014 15:18:34 GMT
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Last-Modified: Fri, 02 May 2014 20:55:47 GMT
Server: nginx/1.6.0
Connection: keep-alive

Hooray, the headers are there!

Mac OSX Development Environment Setup after Archive and Restore

After a few years of owning my Mac, I started to feel that maybe, just maybe, it might be a little slower than it used to be. If nothing else, too many failed late night experiments had led to me installing weird systemy things that didn’t always entirely want to go away.

To clean up my baby, I tried out the ‘Archive and Restore’ feature found on my Mac DVD. It reinstalls OSX Leopard replacing the old instance and attempts to leave all of your application and profile settings just how they were.

Upon completion, I am certainly running smoother and faster, but sadly some of my web development setup got broken along the way.

So that it’s clear, my environment involves using these primary components:

  • MySQL
  • Ruby on Rails
  • Apache/Passenger

Here’s an account of what I did to restore my environment to working order:

MySQL, Git

First step, I followed Dan Croak’s setup guide for the following steps (Ruby and RubyGems were already working fine btw):

  • XCode Tools
  • MySQL
  • Git


Then I recovered the following files from my Time Machine backup:

  • /usr/local/mysql/data (to get my dev databases back)
  • /etc/hosts (to get my local ip shortcuts back)
  • /etc/apache2/httpd.conf (to get my apache/passenger settings back)

If you didn’t backup your Apache/Passenger config, you’ll want to re-run

sudo passenger-install-apache2-module

and probably follow John Ford’s Apache setup guide to get Passenger working for you again.

TextMate integration

Redo this for TextMate’s mate command in console:


I also consulted Neil Ang’s blog to get locate working again.
There’s also a way to make it use Spotlight’s index if you check the comments, however this prevents searching directories such as /usr and /bin, but it can be fun if you want locate to follow your Spotlight preferences for search restrictions.

That’s it! Now I’m back to work. I hope this helps someone else out there.

Development Tips using Passenger for Rails

I’ve just recently set up my rails development environment to be managed by Passenger, and I have to say I like being able to type in real URL’s for my domains and not have to manually start my sites.

However, having formerly done my development by first running “script/server” and then going to town, I miss having the log output handy for whenever I blow something up.

If you’ve made the transition to Passenger I imagine you might also feel the same way, so let’s get that back! The easiest way is to use

tail -f log/development.log

Much better! Now we can see the server log output again so it’s easy to view the stack traces for our bugs. However, now that we’re up and running with our super slick hyped-up toy called ‘Passenger’… we’re still having to take just as many steps to get the same results! In fact, typing that command takes longer than script/server used to take.

Well let’s just fix all of our problems in one fell swoop. Add the following to your .bash_login file:

alias go='cd ~/Sites/newcoolsite.com;> log/development.log;mate .;open -a FireFox http://newcoolsite/staff;tail -f log/development.log;'

…where ‘newcoolsite’ is the directory/domain that you’re interested in. Now when we open up our terminal, we just type ‘go’, hit enter, and in about half a second we’ll find the following has happened:

  1. Our terminal has moved to the proper folder for our site (~Sites/newcoolsite.com)
  2. The development log is cleared
  3. TextMate opened our code
  4. FireFox opened our site (http://newcoolsite/)
  5. Our terminal started monitoring the server log output

Much better! However there’s still one thing bugging me. We used to just hit Ctrl+C then Up and Enter to restart script/server. It was a very quick and easy way to restart the server and keep our terminal window showing us the activity that we want to see. At this point we still have to type

touch tmp/restart.txt
tail -f log/development.log

Unacceptable!! We can easily remedy this situation. Just add a new line to our .bash_login file resulting in the following:

alias go='cd ~/Sites/newcoolsite.com;> log/development.log;mate .;open -a FireFox http://newcoolsite/staff;tail -f log/development.log;'
alias rs='> log/development.log;touch tmp/restart.txt;tail -f log/development.log;'

Now we just hit Ctrl+C, then rs to restart the server and resume our server log monitoring.

Very smooth and painless. Happy coding!

Building Named Scopes Conditionally

I recently ran across an article at Caboose.se about building named scopes conditionally to make a slick filter. Unfortunately comments on it are closed now. The code he shared looked like this:

def index
  scopes = []
  scopes << [ :by_user, params[:user_id] ] if params[:user_id]
  scopes << [ :tag_name, params[:tag_name] ] if params[:tag_name]
  scopes << [ :rating, params[:rating] ] if params[:rating]

  order = { 'name' => 'videos.name ASC' }[params[:order]] || 'videos.id DESC'

  @videos = scopes.inject(Video) {|m,v| m.scopes[v[0]].call(m, v[1]) }.paginate(:all, :order => order, :page => params[:page])

I found this code soon after writing something similar for myself, and modifying his code to look like mine would give:

def index
  scope = Video
  scope = scope.by_user params[:user_id] if params[:user_id]
  scope = scope.tag_name params[:tag_name] if params[:tag_name]
  scope = scope.rating params[:rating] if params[:rating]

  order = { 'name' => 'videos.name ASC' }[params[:order]] || 'videos.id DESC'

  @videos = scope.paginate(:all, :order => order, :page => params[:page])

With this there’s no need for the inject/call, you just call the methods yourself, and skip building an array of symbols/strings. I’m sure this is more efficient, but does this make it more or less readable to you?

I saw Ryan Bates post a response to his article suggesting one could use his scope builder plugin which would turn the code into this:

def index
  scope = Video.scope_builder
  scope.by_user params[:user_id] if params[:user_id]
  scope.tag_name params[:tag_name] if params[:tag_name]
  scope.rating params[:rating] if params[:rating]

  order = { 'name' => 'videos.name ASC' }[params[:order]] || 'videos.id DESC'

  @videos = scope.paginate(:all, :order => order, :page => params[:page])

Seems like a very small gain for the introduction of a plugin. Am I missing something? Are there other examples where my solution would not be as attractive? Or is this a case where the original Rails code suits the purpose just fine?

Mock Expectation Fails on Associated Model (Association Proxy)

I just hit a real mean snag today trying to put an expectation on a model and it didn’t get caught like it should. This is something I do all the time so I knew I wasn’t just making a basic typo. Here’s what my setup looked like:

The model

def purchase
def send_shipping_notice
  puts "hi"

In my spec/test

def given_bought_on(date)
  wp = @order.product
  puts wp.inspect

The output

#<Product id: 270, owner_id: 270, name: 'thing'>

Spec::Mocks::MockExpectationError in 'Product should purchase'
Mock 'Product' expected :send_shipping_notice with (any args) once, but received it 0 times
./spec/models/product_spec.rb:21:in `given_bought_on'

So as you can see, I put an expectation on the wp variable, and verify it gets called by seeing ‘Hi’ get printed. However the expectation totally gets overlooked and my test framework complains that it never happened.

The catch is that the wp in my test and the web_page self inside the model are two different models. So the expectation is on a different model. Calling .object_id or .inspect on either one will affirm (or rather lie) to you that they’re the same, but they are not.

This is (as I’m told) well documented in ActiveRecord and is intentional by design. The wp variable is in fact an Association Proxy, not the WebPage I think it is. It just lies to you outright so you think it’s a WebPage.

My solution, while rather a hack, is the only thing I know to get my spec to pass:

def given_bought_on(date)
  wp = Product.find(@order.product_id)
  puts wp.inspect

Now it grabs the model directly and there’s no confusion.

Rails Pagination by Letters (not Numbers like will_paginate)

I want my list of data to be paginated by letters. The will_paginate plugin certainly gives excellent pagination if all you want is “prev 1 2 3 .. 6 next” kind of pagination.

However what if you’re looking for entries that start with the letter H and you have no idea if that’s page 4 or page 42? You’re probably wanting something more like “# A B C D…” pagination.

I did some googling and found people speaking of solutions for “A B C D…” but in my case, not all of my entries start with letters! If you have something like media titles in your data set, having an entry start with a number is perfectly normal. Some might even start with special characters! Some people suggest having an ‘All’ option, but if you need pagination, it’s probably because you have enough data that showing all options at once is a very bad idea.

Here’s my solution:

First I make a helper function for my options that’ll be cached permanently.

def letter_options
  $letter_options_list ||= ['#'].concat(("A".."Z").to_a)

Here’s my index action in my controller:

@letter = params[:letter].blank? ? 'a' : params[:letter]
if params[:letter] == '#'
  @data = Model.find(:all, :conditions => ["title REGEXP ?", 
      "^[^a-z]"], :order => 'title', :select => "id, title")
  @data = Model.find(:all, :conditions => ["title LIKE ?", 
      "#{params[:letter]}%"], :order => 'title', :select => "id, title")

Here’s my html

<div class ="pagination">
  <% letter_options.each do |letter| %>
    <% if params[:letter] == letter %>
      <span class="current"><%= letter %></span>
    <% else %>
      <%= link_to letter, staff_games_path(:letter => letter)%>
    <% end %>
  <% end %>

There we go! Now the # will pull up all entries where the first character is not a letter.

Attachment Fu and Zip Files – RubyZip and Extracting For Bulk Uploads

Today I’m going to share how you can let your app accept zip files which will then be extracted into multiple attachments. If you already use Attachment Fu to manage files, this should be super easy to add.

Before my controller had something like this:

Attachment.create(:uploaded_data => params[:Filedata])

First break that up into something more like this:

attachment = Attachment.new
attachment.uploaded_data = params[:Filedata]

Then put in some split logic for if it’s a zip file:

attachment = Attachment.new
attachment.uploaded_data = params[:Filedata]
if attachment.content_type == "application/zip"
    # Unzip this and process all the inner files

Now we’ll need the RubyZip gem and MIME Types gem, so do:

sudo gem install rubyzip
sudo gem install mime-types

Now in the Attachment class we’ll add the build_from_zip method:

def self.build_from_zip(ss)
 zipfile = Zip::ZipFile.open(ss.temp_path)
 zipfile.each do |entry|
   if entry.directory?
   elsif entry.name.include?("/")
     screen = Attachment.new
     screen.filename = entry.name
     screen.temp_data = zipfile.read(entry.name)
     mime = MIME::Types.type_for(entry.name)[0]
     screen.content_type = mime.content_type unless mime.blank?


The only two non-obvious things to note here are:

  • I skip the files with / in them because when I archive files on my machine, hidden files with / characters in them make it into the archive. I only want the real files.
  • I use the MIME Types gem to decide the content type from the filename.

I hope you find this helpful, enjoy!

IE6 vs JavaScript (Prototype) and Sortable Elements Hidden/Disappearing/Invisible

Today I have another IE6 quirk in dealing with Prototype. I have a bunch of elements that I want to sort with a Sortable object, which works as expected for the most part, except in IE6!

I set background-color: #E6F2FF; to the rows of my ‘table’ which of course isn’t a real table, just some nicely styled div’s! The problem with this is that there’s a bug in this situation with IE6. All the contents of my rows are hidden! That means text, links, images. It looks as if all of the rows are just empty… except I can mouse-over and my mouse can interact with the elements.

It turns out, the opacity css attribute is 0. Or at least IE6 behaves as if it is. The thing is, FireBug doesn’t agree, and if you set opacity: 1; in your stylesheet it won’t cut it. The problem begins just after the Sortable.Create call. Removing this call fixes the problem, obviously, but that’s not what we want!

Here’s my solution. After the Sortable.Create call, do this:

if (Prototype.Browser.IE) {
    $$('.relevant_class_name').invoke.setStyle({opacity: 1});

where relevant_class_name is the css class assigned to the row’s of data on my page. This sets the opacity to all of the affected elements after the the Sortable object screws things up.

Hooray! I hope this helps someone else.

IE vs JavaScript (Prototype) and position: relative

In the current project I’m working on I have all sorts of cool AJAX madness happening to add things to my pages. For one particular example, I have AJAX calls that add pieces to the page with more AJAX functions inside of those pieces. Fun, huh?

The kicker is that some of the elements on the page there are being shown with the style attribute of position: static;. It just so happens that Prototype and position: static do not always play nicely in this case.

Let me show you what I mean. Here you see an image with two links placed with position: static;.

Clicking on “+ Add Foo” twice and “+ Change Bar” gives:

This works as expected. However if I add a duplication of this segment of the page using an AJAX call, the new portion does not work as expected while in Internet Explorer (every other browser works just fine of course).

To illustrate the problem while trying to do the same thing with the new segment, first I add the new segment via the “+ Add Many Things” link.

Then I click “- Change Bar” which hides the following two lines. You now see the two links I’ve been referring do not follow the movement of the page. They should have scrolled up and they did not.

To handle this, I need some extra JavaScript. First I add the following to the parameters of my AJAX call:

onSuccess: function(request){ reposition(); }

Next I want to take the elements that I know I have this problem with (selected by class name) and then first turn off the “relative” position by setting it to “static” and then back to “relative” again. By the way I figured this out thanks to way too much time fiddling with things in FireBug and the IE Dom Inspector. I can’t come up with any real sense to it. To make this happen, I add the following JavaScript for IE only:

function reposition() {
  if (Prototype.Browser.IE) {
function swapStaticToRelative(item) {
	item.setStyle({ position: 'static' });
	item.setStyle({ position: 'relative' });

Note that the following also works for detecting that the browser is any version of IE:

function reposition() {
          /*@if (@_win32)
          @else @*/

I wish I could remember where I found that, but it’s crazy cool. Sure the Prototype way is better… but this is a fun one to stare at for a while until you figure out how it’s working.

So with that change in place, this time it works as expected.

The only thing better I think (aside from IE not sucking) would be to have a way to select fields by style attributes. If I could figure that out, I’d be able to make a single call to swap these CSS attributes for all instances on the page that are relevant to this problem. If I could do that, then it might be a candidate for a patch to Prototype.

If you have a suggestion for a better way to handle this or if my post helped you out, please let me know by leaving a comment!

Easy PlainText Stories in Ruby on Rails using WebRat

Building off of my last post on Stories, I’d like to show you some improvements I was able to make with the help of WebRat.

You can install WebRat using:

script/plugin install http://svn.eastmedia.net/public/plugins/webrat/

I got the inspiration from Ben Mabey at ‘ben.send :blog’ which illustrates an approach to stories that is unbelievably easy to pick up. He also provides source code to the example that he’s built so that you can play with it. Very cool!

I snagged that source myself and started playing with it, and added a lot of functionality of my own that I found useful. The real cool thing is that the ONLY application specific code I have is this:

# user_steps.rb
steps_for(:user) do
  Given("that $actor is not logged in") do |actor|
    get "/sessions/destroy"
    response.should be_redirect
    flash[:notice].should == "You have been logged out."

    #fails here even though in the next request it will pass
    #controller.should_not be_logged_in
  Then("$actor $should be logged in") do |actor, should|
    controller.send(shouldify(should), be_logged_in)

# navigation_steps.rb
def path_from_descriptive_name(page_name)
  case page_name
  when "home"
  when "signup"
  when "login"

With that, and the generic application-independent helper methods that also live in my steps directory, I can write the following story:

Story: Making posts

  As a visitor
  I want to be a member
  So that I can make posts

    Scenario: Glenn creates a new account
      Given that Glenn is not logged in
      And there are some number of users
      And no user with login 'Glenn' exists
      When he goes to the signup page
      And fills in Login with 'Glenn'
      And fills in Email with 'glenn@glennfu.com'
      And fills in Password with 'blah'
      And fills in Confirm Password with 'blah'
      And clicks the 'Sign up' button

      Then there should be 1 more user
      And a user with login 'Glenn' should exist

    Scenario: Glenn logs in
      GivenScenario Glenn creates a new account

      When Glenn goes to the login page
      And fills in Login with 'Glenn'
      And fills in Password with 'blah'

      Then he should be logged in
    Scenario: A member makes a post while logged in
      GivenScenario Glenn logs in
      And there are some number of posts

      When he goes to the posts page
      And clicks on 'New post'
      And fills in Title with 'Woo'
      And fills in body with 'Stuff here'
      And clicks the 'Create' button

      Then there should be 1 more post
      And a post with title 'Woo' should exist

    Scenario: A nice lady makes a post while not logged in
      Given that she is not logged in
      Then she should not be logged in

      Given there are some number of posts

      When she goes to the posts page
      And clicks on 'New post'

      Then she should see the login page

    Scenario: An angry visitor should be able to see posts
      Given that he is not logged in

      When he goes to the posts page

      Then he better not f'ing see the login page

    Scenario: A visitor should not be able to edit posts
      GivenScenario A member makes a post while logged in
      And that she is not logged in

      When she goes to the posts page
      And clicks on 'Edit'

      Then she should see the login page

Pretty cool, huh? I was even able to add some personality with the angry visitor Scenario. Notice that I don’t have any steps written about Posts or my PostsController. I don’t need it because I have generic model steps that parse the model from the text in my PlainText instructions. It has all the basics that you need. You interact with forms and links on the top level by name, and then check the results either by text on the page or by finding models.

If you’d like to play with it yourself, I’ve zipped up my stories folder for you to play with.

Download it here!

It also has the old user_story.rb from the previous example. If you have any suggestions for improvements to this or ideas for something else I should do with it, please leave a comment!

My only quirk with this is that if you check the first step in the steps_for(:user) above you’ll see I have a line commented out. It checks for controller.should_not be_logged_in and if I uncomment it, the check fails even though the two above it pass. As you can see in the PlainText, on the very next line I call the very same check and it passes. If you could help me figure out my mistake here I’d really appreciate you leaving a comment with your thoughts!

I hope you find this useful, and if so, be sure to go toss a thank you over to Ben for the inspiration.