Fix Rcov After Upgrade Rspec to 2.8

RubyOnRails 14 一月 2012 | View Comments

Rcov doesn’t work after I upgrade rspec to 2.8,

here is a quick fix

add following code into your spec_helper

<div id="_mcePaste">require 'rspec/autorun'</div>

Tagged in ,

Use Paperclip in rack app like sinatra and how to write test

Tips,ruby 8 十一月 2011 | View Comments

You’ll find rack parse uploaded file in different format to Rails

Here is the format in rack app.

"image"=>{:type=>"image/jpeg", :filename=>"listing[image]", :tempfile=>#<File:/tmp/RackMultipart20111107-16008-erra0z-0>, :head=>"Content-Disposition: form-data; name=\"listing[image]\"; filename=\"listing[image]\"\r\nContent-Type: image/jpeg\r\n", :name=>"listing[image]"}

You can simply covert it to right format.

post "some_api" do
yourModel = YourModel.new(:image => to_paperclip(params['image']))
yourModel.save
end
def to_paperclip(image)
  paperclip = {}
  paperclip['tempfile'] = image[:tempfile]
  paperclip['filename'] = image[:filename]
  paperclip['content_type'] = image[:type]
  paperclip['size'] = image[:tempfile].size
  paperclip
end

How to test

 filename = Rails.root.join "spec/fixtures/rails.png"
 file = Rack::Test::UploadedFile.new(filename, "image/png")
 post "/api/v1/some_api", {:image => file}
 # should have image uploaded

Tagged in , , ,

Cocoa Non-Blocking sleep wait background task

iOS Dev 30 十月 2011 | View Comments

If you have some async task running in background, and you need wait this background task until it finished, code below will help u:

 NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
    while (![self isFinished] && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:loopUntil]) {
        loopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
    }

Tagged in , ,

Restkit Parse ActiveRecord Timestamp

Restkit,RubyOnRails,iOS Dev 28 十月 2011 | View Comments

If you are using Rails as your backend, Reskit will have trouble to parse ActiveRecord timestamp.

Default ActiveRecord timestamp JSON out is 2008-12-29T00:27:42-08:00

You can not convert it to NSDate directly use NSDateFomatter
you must convert it to 2008-12-29T00:27:42-0800

But you have not chance to convert when you use Restkit Mapping.

Here is my solution
1. Monkey patch Time and DateTime class

class Time
  def as_json(option=nil)
    self.strftime("%Y-%m-%dT%H:%m:%S%z")
  end
end
class DateTime
  def as_json(format=nil)
    self.strftime("%Y-%m-%dT%H:%m:%S%z")
  end
end

2. Add default date fomatter to RKObjectMapping

    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    [RKObjectMapping addDefaultDateFormatter:dateFormatter];

Tagged in , ,

Fix gcc issue after install xcode 4.2

iOS Dev,ruby 28 十月 2011 | View Comments

I can not install gem after installed xcode 4.2. It throws bus error.

the problem is xcode replace gcc with llvm-gcc

How to fix it:
1. Install standalone gcc
http://cloud.github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg

2. add gcc environment in your bash

export CC=/usr/bin/gcc-4.2

Tagged in ,

Three20 – Use TTImageView instead of UIImageView showing remote image

Three20,iOS Dev 6 十月 2011 | View Comments

Thee20 is very good framework.

The features of TTImageView
1. Load image from remote
2. Support default image
3. Cache image, so you don’t need load it again.
4. Support reload image

Find more to read source code of TTImageView

#import <Three20/Three20.h>
TTImageView *productImage = [[TTImageView alloc] initWithFrame: CGRectMake(30, 30, 70, 70)];
[productImage setUrlPath:@"http://a-image-url"];
[productImage setDefaultImage:[UIImage imageNamed:@"default_product_small.png"]];

Tagged in , , , ,

Devise Do Not Redirect to Login Page When Session Timeout

RubyOnRails 4 六月 2011 | View Comments

By default, devise will redirect to login path if session timeout.

So user will redirect to login path when visit page do not need login after session timeout.

To solve this problem you can follow these steps:

  • Set custom failure app, modify code at the end of config/initializers/devise.rb
config.warden do |manager|
    manager.failure_app   = DeviseFailureApp
  end
  • create your custom failure app DeviseFailureApp
class DeviseFailureApp < Devise::FailureApp
  def redirect
    message = warden.message || warden_options[:message]
    if message == :timeout
      redirect_to attempted_path
    else
      super
    end
  end
end

Tagged in ,

Tips – Use Named Routes outside of Controller and View

RubyOnRails,Tips,ruby 27 四月 2011 | View Comments

class UrlWriterSingleton
  include Singleton
  include ActionController::UrlWriter

  def self.default_url_options
    {:host => 'www.seravia.com'}
  end
end

module NameRouteHelper
  def self.included(base)
    base.send(:include, InstanceMethods)
  end

  module InstanceMethods
    def name_path_for(name, options = {})
      UrlWriterSingleton.instance.send("#{name}_path", options)
    end
  end
end

Usage:

Class TestNamedRouteHelper
  include NameRouteHelper
end

TestNamedRouteHelper.new.name_path_for("root")

Tagged in , ,

Rspec Tips – Implicit Subject “its”

ruby 7 四月 2011 | View Comments

Rspec has a convenient way to write simple test

describe [1, 2, 3, 3] do
  its(:size) { should == 4 }
  its("uniq.size") { should == 3 }
end

Tagged in , ,

Testing Tips – Prepare Test in Setup

ruby 20 三月 2011 | View Comments

Let’s look at a bad example first:

  context "generate index table" do
    should "success" do
      input_file_path  = "input.json" # have 1,000 lines
      output_file_path = "output.json"
        expact_file_path = "expect.json"
        DataTransform::Mongo::IndexTable.run(input_file_path, output_file_path)
        expect_lines = open(expect_file_path).readlines
        real_lines = open(real_file_path).readlines
      real_lines.each_with_index do |line, index|
      assert_equal JSON.parse(expact_lines[index],line)
      end
    end
  end

What’s the problem in previous test code?

  1. I can not fix this test if it fail
  2. I don’t know what is this test testing

How to refactor this test?

  1. Prepare data in setup
  2. Naming test better
  context "generate index table from standard input" do
    setup do
      @input_file_path  = "input.json"
      @output_file_path = "output.json"
      data = [
        {:a => 1, :b => 1},
        {:a => 2, :b => 3},
        {:a => 3, :b => 4}
      ]

      File.open(@input_file_path) do |f|
        data.each do |line|
          f.puts(JSON.encode(line))
        end
      end
    end
    should "tranform 'a' to 'keyword', 'b' to 'owner'" do
      DataTransform::Mongo::IndexTable.run(@input_file_path, @output_file_path)
      out_file = File.new(@output_file_path)
      expect_data = [
        {:keyword => 1, :owner => 1},
        {:keyword => 2, :owner => 3},
        {:keyword => 3, :owner => 4}
      ]
      assert_equal expect_data.size, outfile.lines.size
   
      real_data = []
      out_file.each_line do |line|
        real_data << JSON.decode(line)
      end
      assert_equal expect_data,real_data
      end
    end
  end

Tagged in , ,

Ads Plugin created by Jake Ruston's Wordpress Plugins - Powered by and football database.