OSDN Git Service

add json parser on common
authoryasushiito <yas@pen-chan.jp>
Tue, 19 Jun 2012 07:08:04 +0000 (16:08 +0900)
committeryasushiito <yas@pen-chan.jp>
Tue, 19 Jun 2012 07:08:04 +0000 (16:08 +0900)
lib/common.rb [new file with mode: 0644]
lib/test/common_spec.rb [new file with mode: 0644]

diff --git a/lib/common.rb b/lib/common.rb
new file mode 100644 (file)
index 0000000..44ebcdf
--- /dev/null
@@ -0,0 +1,14 @@
+require 'json'
+
+module JSON
+  def self.parse_no_except(data)
+    res = data
+    begin
+      res = JSON.parse(data) if data.is_a?(String)
+    rescue 
+      return false
+    end
+    res
+  end
+end
+  
diff --git a/lib/test/common_spec.rb b/lib/test/common_spec.rb
new file mode 100644 (file)
index 0000000..5a699f2
--- /dev/null
@@ -0,0 +1,29 @@
+# -*- encoding: utf-8 -*-
+#共通処理
+require 'common'
+
+describe JSON do
+  before do
+  end
+
+  describe '例外なしパースに於いて' do
+    context 'テキストを渡されたとき' do
+      it 'Json解析している' do
+        JSON.should_receive(:parse).with(any_args).exactly(1)
+        r = JSON.parse_no_except '{}'
+      end
+      it '単数データならHashで返す' do
+        r = JSON.parse_no_except '{}'
+        r.is_a?(Hash).should be_true
+      end
+    end
+    context 'パース失敗したとき' do
+      it 'Falseを返す' do
+        JSON.should_receive(:parse).with(any_args).and_raise('StandardError')
+        r = JSON.parse_no_except ''
+        r.should be_false
+      end
+    end
+  end
+end
+