下記URLから入手できます。
http://svn.s21g.com/public/rails/plugins/tinyurl_helper/

###仕様
URLを渡すとTinyURLに変換してリンクを作ります。

###使い方

  • application_helper.rbでinclude
    rails>>
    module ApplicationHelper
    include TinyurlHelper
    end
    <<--
  • View内で
    rails>>
    <%= link_to_tinyurl "http://www.yahoo.co.jp" %>
    <<--

###作り方
0. 類似するプラグインを探してコーディングの検討をつける

  1. script/generateする
    shell>>
    script/generate plugin tinyurl_helper
    <<--
  2. 上で生成されたlib/tinyurl_helper.rbを編集
    rails>>
    require 'net/http'

module TinyurlHelper
def link_to_tinyurl(url, html_options = nil)
uri = 'http://tinyurl.com/api-create.php?url=' + url
uri = URI.parse(uri)
tiny_url = Net::HTTP.get_response(uri).body
options = {:title => url, :alt => url}
options = html_options.nil? ? options : options.merge(html_options)
link_to tiny_url, tiny_url, options
end
end
<<--
3. テストを書く(アプリテスト、プラグイン単体テスト両方通るように書くと吉)

rails>>

require 'test/unit'
require File.expand_path(File.dirname(FILE) + "/../lib/tinyurl_helper")

class TinyurlHelperTest < Test::Unit::TestCase
include TinyurlHelper

#dummy link_to
def link_to(name, options = {}, html_options = nil)
[name, html_options[:title]]
end

def test_link_to_tinyurl
url = 'http://www.yahoo.co.jp/'
tiny_url, title = link_to_tinyurl(url)
assert_equal 'http://tinyurl.com/910', tiny_url
assert_equal url, title
end

def test_link_to_tinyurl_with_title
url = 'http://www.yahoo.co.jp/'
tiny_url, title = link_to_tinyurl(url, {:title => 'title'})
assert_equal 'http://tinyurl.com/910', tiny_url
assert_equal 'title', title
end
end
<<--

  1. README, MIT-LICENSEを書く
  • READMEは名前と、概要・使い方を書く
  • MIT-LICENSEは名前だけ変更
  1. 公開用リポジトリにコミット
  2. pluginディレクトリに登録する

###Tips

  • プラグインはweb serverを再起動しないとリロードされない
  • helperを使えるようにする方法は2つ
  1. app/helper/application_helper.rbでinclude(上でやった方法)
  2. plugins/tinyurl_helper/init.rbでsendする
    rails>>
    ActionView::Base.send :include, TinyurlHelper
    <<--
posted by satoko satoko on Tue 26 Feb 2008 at 06:20 with 0 comments