[from now] Wed May 21 08:31:48 JST 2014

diff --git a/Gemfile b/Gemfile
index 8afa16f..601a56c 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,2 +1,7 @@
-gem "amazon-ecs"
-gem "json"
+source 'https://rubygems.org'
+
+gem 'amazon-ecs'
+gem 'json'
+gem 'rspec'
+gem 'activesupport'
+gem 'builder'
diff --git a/lib/lokka/amazon_associate.rb b/lib/lokka/amazon_associate.rb
index 50e0bb8..a88d7e3 100644
--- a/lib/lokka/amazon_associate.rb
+++ b/lib/lokka/amazon_associate.rb
@@ -3,6 +3,7 @@ require 'amazon/ecs'
 require 'nokogiri'
 require 'fileutils'
 require 'json'
+require_relative 'amazon_associate/fetcher'

 module Lokka
   module AmazonAssociate
@@ -14,7 +15,7 @@ module Lokka
       app.put '/admin/plugins/amazon_associate' do
         Option.associate_tag = params['associate_tag']
         Option.access_key_id = params['access_key_id']
-        Option.secret_key = params['secret_key']
+        Option.secret_key    = params['secret_key']
         flash[:notice] = 'Updated.'
         redirect '/admin/plugins/amazon_associate'
       end
@@ -32,11 +33,16 @@ module Lokka

   module Helpers
     def associate_link(entry)
-      entry.gsub(/<!--\s(?:ISBN|ASIN)=([0-9A-Z]+?)\s-->/m) {
-        item = get_path($1)
-        json = parse_item(item)
-        format_item(json)
-      }
+      regexp = /<!--\s(?:ISBN|ASIN)=([0-9A-Z]+?)\s-->/
+      matches = entry.scan(regexp).flatten
+      matches.each do |item_id|
+        item = AmazonAssociate::Fetcher.new(item_id)
+        next if item.blank?
+        element = format_item(item.body)
+        entry.gsub!(/<!--\s(?:ISBN|ASIN)=#{item_id}\s-->/, element)
+      end
+
+      entry
     end

     def format_item(json)
@@ -46,60 +52,33 @@ module Lokka
         return @error = "#{error["Code"]}: #{error["Message"]}" if error.present?
         item = json["ItemLookupResponse"]["Items"]["Item"]
         attr = item["ItemAttributes"]
-        @title = h! attr["Title"] rescue nil
-        @link  = item["DetailPageURL"] rescue nil
+        @title = h!(attr["Title"])         rescue nil
+        @link  = item["DetailPageURL"]     rescue nil
         @image = item["LargeImage"]["URL"] rescue nil
         @price = item["OfferSummary"]["LowestNewPrice"]["FormattedPrice"] rescue "-"
         authors = []
-        authors << format_authors(attr["Creator"]) if attr["Creator"]
-        authors << format_authors(attr["Author"]) if attr["Author"]
+        authors << format_authors(attr["Creator"])  if attr["Creator"]
+        authors << format_authors(attr["Author"])   if attr["Author"]
         authors << format_authors(attr["Director"]) if attr["Director"]
-        authors << format_authors(attr["Actor"]) if attr["Actor"]
-        authors << format_authors(attr["Artist"]) if attr["Artist"]
+        authors << format_authors(attr["Actor"])    if attr["Actor"]
+        authors << format_authors(attr["Artist"])   if attr["Artist"]
         @author = h! authors.join(", ") if authors.present?
         @manufacturer = attr["Manufacturer"]

         haml :'plugin/lokka-amazon_associate/views/tag', :layout => false
       rescue => e
-        "#{e}: malformed JSON"
+        puts e
       end
     end

     def format_authors(authors)
       if authors.class == Array && authors.size > 1
-        authors.inject([]) { |authors, item|
+        authors.inject([]) {|authors, item|
           authors << item
         }.join(", ")
       else
         authors
       end
     end
-
-    def get_item(item_id, *args)
-      args = {:country => :jp, :response_group => 'Medium'} if args.blank?
-      Amazon::Ecs.options = {
-        :associate_tag => Option.associate_tag,
-        :AWS_access_key_id => Option.access_key_id,
-        :AWS_secret_key => Option.secret_key
-      }
-      Amazon::Ecs.item_lookup(item_id, args)
-    end
-
-    def get_path(item_id)
-      dir = File.expand_path("tmp/amazon")
-      path = File.join(dir, item_id)
-      FileUtils.mkdir_p(File.dirname(path))
-      return path if File.exists?(path) && File.stat(path).mtime > Time.now.yesterday
-      open(path, "w") { |f|
-        item = get_item(item_id)
-        f.print Hash.from_xml(item.doc.to_xml).to_json
-        sleep 1
-      }
-      path
-    end
-
-    def parse_item(path)
-      JSON.parse(File.read(path))
-    end
   end
 end
diff --git a/spec/factories.rb b/spec/factories.rb
deleted file mode 100644
index d59d8fc..0000000
--- a/spec/factories.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-FactoryGirl.define do
-  create_time = update_time = Time.parse("2011-01-09T05:39:08Z")
-
-  factory :user do
-    sequence(:name){|n| "testuser#{n}" }
-    hashed_password '6338db2314bba79531444996b780fa7036480733'
-    salt '2Z4H4DzATC'
-    permission_level 1
-    created_at create_time
-    updated_at update_time
-  end
-end
diff --git a/spec/lib/amazon_associate_spec.rb b/spec/lib/amazon_associate_spec.rb
deleted file mode 100644
index 60b8e80..0000000
--- a/spec/lib/amazon_associate_spec.rb
+++ /dev/null
@@ -1,79 +0,0 @@
-#-*- coding: utf-8 -*-
-require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
-
-describe Lokka::Helpers do
-  describe "#associate_link" do
-    context "本文中にISBN/ASINタグがあればアフィリエイトリンクに変換する" do
-      it "ISBN タグをリンクに変換する" do
-        associate_link("これはテストです。\n\n<!-- ISBN=UNKOSHITAIYO -->\n\n終わり。").should match(/amazon-image/)
-      end
-
-      it "ASIN タグをリンクに変換する" do
-        associate_link("これはテストです。\n\n<!-- ASIN=UNKOSHITAIYO -->\n\n終わり。").should
-      end
-    end
-  end
-
-  describe "#format_item" do
-    it "json を HTML として出力する"
-  end
-
-  describe "#format_authors" do
-    it "著者名を整形する'"
-  end
-
-  describe "#get_item" do
-    it "item_id とオプションを受け取って検索結果を返す"
-  end
-
-  describe "#get_path" do
-    it "item_id を受け取ってパスを返す"
-  end
-
-  describe "#parse_item" do
-    it "does something"
-  end
-end
-
-=begin
-describe Lokka::AmazonAssociate do
-  before do
-    FactoryGirl.create(:user, :name => 'test')
-  end
-
-  context "GET /admin/plugins/amazon_associate" do
-    subject do
-      get "/admin/plugins/amazon_associate"
-      last_response
-    end
-
-    it "should be success" do
-      subject.shuold be_success
-    end
-
-    it "should match \"Amazon Associate\"" do
-      subject.body.should match('Amazon Associate')
-    end
-  end
-
-  context "PUT /admin/plugins/amazon_associate" do
-    before do
-      put "/admin/plugins/amazon_associate",
-      { :associate_tag => "portalshit-22",
-        :access_key_id => "access_key_id",
-        :secret_key => "secret_key" }
-      end
-
-      it "should be success" do
-        last_response.should be_success
-      end
-
-      it "parameters should have correctly saved" do
-        Option.associate_tag.should == "portalshit-22"
-        Option.access_key_id.should == "access_key_id"
-        Option.secret_key.shuold = "secret_key"
-      end
-    end
-  end
-end
-=end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 1892818..131f04d 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -4,7 +4,6 @@ ENV['BUNDLE_GEMFILE'] ||= File.expand_path(File.dirname(__FILE__) + '/../Gemfile
 require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
 Bundler.require :default if defined?(Bundler)

-require_relative 'factories'
-
 $:.unshift File.expand_path(File.dirname(__FILE__) + '/../lib')
 require "lokka/amazon_associate"
+require 'active_support/all'