Initial working version of the BurstNet test API.

This commit is contained in:
2013-06-02 16:06:53 +01:00
commit 74d5b88ecd
34 changed files with 611 additions and 0 deletions

15
.gitignore vendored Normal file
View File

@@ -0,0 +1,15 @@
\#*
*~
.#*
.DS_Store
.idea
.project
.sass-cache
coverage
Gemfile.lock
tmp
nbproject
pkg
*.swp
spec/dummy
config/initializers/burst_net.rb

1
.rspec Normal file
View File

@@ -0,0 +1 @@
--color

1
.ruby-gemset Normal file
View File

@@ -0,0 +1 @@
spree2

1
.ruby-version Normal file
View File

@@ -0,0 +1 @@
1.9.3

8
Gemfile Normal file
View File

@@ -0,0 +1,8 @@
source 'https://rubygems.org'
# Provides basic authentication functionality for testing parts of your engine
gem 'spree_auth_devise', github: 'spree/spree_auth_devise', :branch => '2-0-stable'
gemspec
gem 'httparty'

26
LICENSE Normal file
View File

@@ -0,0 +1,26 @@
Copyright (c) 2013 [name of plugin creator]
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Spree nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

40
README.md Normal file
View File

@@ -0,0 +1,40 @@
SpreeBurstnet
=============
Introduction goes here.
Installation
------------
Add spree_burstnet to your Gemfile:
```ruby
gem 'spree_burstnet'
```
Bundle your dependencies and run the installation generator:
```shell
bundle
bundle exec rails g spree_burstnet:install
```
Testing
-------
Be sure to bundle your dependencies and then create a dummy test app for the specs to run against.
```shell
bundle
bundle exec rake test_app
bundle exec rspec spec
```
When testing your applications integration with this extension you may use it's factories.
Simply add this require statement to your spec_helper:
```ruby
require 'spree_burstnet/factories'
```
Copyright (c) 2013 [name of extension creator], released under the New BSD License

15
Rakefile Normal file
View File

@@ -0,0 +1,15 @@
require 'bundler'
Bundler::GemHelper.install_tasks
require 'rspec/core/rake_task'
require 'spree/testing_support/extension_rake'
RSpec::Core::RakeTask.new
task :default => [:spec]
desc 'Generates a dummy app for testing'
task :test_app do
ENV['LIB_NAME'] = 'spree_burstnet'
Rake::Task['extension:test_app'].invoke
end

11
Versionfile Normal file
View File

@@ -0,0 +1,11 @@
# This file is used to designate compatibilty with different versions of Spree
# Please see http://spreecommerce.com/documentation/extensions.html#versionfile for details
# Examples
#
# '1.2.x' => { :branch => 'master' }
# '1.1.x' => { :branch => '1-1-stable' }
# '1.0.x' => { :branch => '1-0-stable' }
# '0.70.x' => { :branch => '0-70-stable' }
# '0.40.x' => { :tag => 'v1.0.0', :version => '1.0.0' }

View File

@@ -0,0 +1 @@
//= require admin/spree_backend

View File

@@ -0,0 +1 @@
//= require store/spree_frontend

View File

@@ -0,0 +1,3 @@
/*
*= require admin/spree_backend
*/

View File

@@ -0,0 +1,3 @@
/*
*= require store/spree_frontend
*/

View File

@@ -0,0 +1,4 @@
module BurstNet
class Backup < BurstNet::Model
end
end

View File

@@ -0,0 +1,4 @@
module BurstNet
class CP < BurstNet::Model
end
end

View File

@@ -0,0 +1,24 @@
module BurstNet
class Product < BurstNet::Model
attr_accessor :id
def initialize(params)
self.id = params['id']
end
def self.all
orders = self.burstnet.get_orders
orders_objs = []
orders['order'].each do |order|
orders_objs << self.new(order)
end
orders_objs
end
# Find a particular product, based on its name
def self.find(id)
order = self.burstnet.get_order(id)
self.new(order['order'])
end
end
end

View File

@@ -0,0 +1,4 @@
module BurstNet
class OS < BurstNet::Model
end
end

View File

@@ -0,0 +1,27 @@
module BurstNet
class Product < BurstNet::Model
attr_accessor :id, :name, :description, :config
def initialize(params)
self.id = params['id']
self.name = params['name']
self.description = params['description']
self.config = params['config'] unless params['config'].nil?
end
def self.all
products = self.burstnet.get_products
products_objs = []
products['product'].each do |prod|
products_objs << self.new(prod)
end
products_objs
end
# Find a particular product, based on its name
def self.find(id)
product = self.burstnet.get_product(id)
self.new(product['product'])
end
end
end

View File

@@ -0,0 +1,34 @@
module BurstNet
class Service < BurstNet::Model
attr_accessor :id, :name, :hostname, :order_id, :status, :product_id, :dedicatedip, :assignedips, :username, :password
def initialize(params)
self.id = params['id']
self.name = params['name']
self.hostname = params['hostname']
self.order_id = params['order']
self.status = params['status']
self.product_id = params['pid ']
self.dedicatedip = params['dedicatedip']
self.assignedips = params['assignedips']
self.username = params['username']
self.password = params['password']
end
def self.all
services = self.burstnet.get_services
services_objs = []
yield services_objs unless services.kind_of?(Array)
services.each do |serv|
services_objs << self.new(serv)
end
services_objs
end
# Find a particular service, based on its name
def self.find(id)
service = self.burstnet.get_service(id)
self.new(service)
end
end
end

View File

@@ -0,0 +1,4 @@
module BurstNet
class Site < BurstNet::Model
end
end

View File

@@ -0,0 +1,3 @@
BurstNet::API.configure do |config|
config[:basic_auth] = {:username => 'username', :password => 'password'}
end

5
config/locales/en.yml Normal file
View File

@@ -0,0 +1,5 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"

3
config/routes.rb Normal file
View File

@@ -0,0 +1,3 @@
Spree::Core::Engine.routes.draw do
# Add your extension routes here
end

View File

@@ -0,0 +1,8 @@
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.timestamps
end
end
end

161
lib/burst_net/api.rb Normal file
View File

@@ -0,0 +1,161 @@
require 'rubygems'
require 'httparty'
require 'json'
=begin BurstNet API methods
GET order
GET order/:id
GET order/active/
GET order/cancelled/
GET order/fraud/
GET order/pending/
GET product
GET product/:id
GET product/backup/
GET product/backup/:id
GET product/cp/
GET product/cp/:id
GET product/os/
GET product/os/:id
GET product/site/
GET product/site/:id
GET service
GET service/:id
GET service/active/
GET service/cancelled/
GET service/fraud/
GET service/pending/
GET service/suspended/
GET service/terminated/
POST order
POST service/:id
PUT service/:id
=end
module BurstNet
class API
include HTTParty
base_uri 'https://rsapi.burst.net'
format :json
headers 'Accept' => 'application/json', 'Content-Type' => 'application/json'
def self.configuration
@configuration ||= {}
end
def self.configure
yield(configuration) if block_given?
end
def initialize
self.class.default_options.merge!(self.class.configuration)
end
def get(path, options = {})
response = self.class.get(path, options)
if response.success?
response.parsed_response
else
raise response.response
end
end
def post(path, options = {})
response = self.class.post(path, options).parsed_response
if response.success?
response.parsed_response
else
raise response.response
end
end
def put(path, options = {})
response = self.class.put(path, options).parsed_response
if response.success?
response.parsed_response
else
raise response.response
end
end
def delete(path, options = {})
response = self.class.delete(path, options).parsed_response
if response.success?
response.parsed_response
else
raise response.response
end
end
def get_products
self.get('/product')
end
def get_product(id)
self.get("/product/#{id}")
end
def get_product_backup(id)
self.get("/product/backup/#{id}")
end
def get_product_cp(id)
self.get("/product/cp/#{id}")
end
def get_product_os(id)
self.get("/product/os/#{id}")
end
def get_product_site(id)
self.get("/product/site/#{id}")
end
def get_services
self.get('/service')
end
def get_service(id)
self.get("/service/#{id}")
end
def terminate_service(id)
self.delete("/service/#{id}")
end
def change_service(id, params)
options = {:body => params}
self.post(id, options)
end
def update_service(id, params)
options = {:body => params}
self.put(id, options)
end
def get_services_by_status(status)
possible_status = %w(active cancelled fraud pending suspended terminated)
raise('Unknown service status') unless possible_status.include?(status)
self.get("/service/#{status}")
end
def get_orders
self.get('/order')
end
def get_orders_by_status(status)
possible_status = %w(active cancelled fraud pending)
raise('Unknown order status') unless possible_status.include?(status)
self.get("/order/#{status}")
end
def get_order(id)
self.get("/order/#{id}")
end
def create_order(params)
options = {:body => params}
self.post(id, options)
end
end
end

7
lib/burst_net/model.rb Normal file
View File

@@ -0,0 +1,7 @@
module BurstNet
class Model
def self.burstnet
@burstnet ||= BurstNet::API.new
end
end
end

15
lib/burst_net_parser.rb Normal file
View File

@@ -0,0 +1,15 @@
class BurstNetParser < Faraday::Response::Middleware
def on_complete(env)
json = MultiJson.load(env[:body], symbolize_keys: true)
json.each do |k, v|
if k == :product
json = v[0]
break
end
end
puts json
env[:body] = {
data: json,
}
end
end

View File

@@ -0,0 +1,31 @@
module SpreeBurstnet
module Generators
class InstallGenerator < Rails::Generators::Base
class_option :auto_run_migrations, :type => :boolean, :default => false
def add_javascripts
append_file 'app/assets/javascripts/store/all.js', "//= require store/spree_burstnet\n"
append_file 'app/assets/javascripts/admin/all.js', "//= require admin/spree_burstnet\n"
end
def add_stylesheets
inject_into_file 'app/assets/stylesheets/store/all.css', " *= require store/spree_burstnet\n", :before => /\*\//, :verbose => true
inject_into_file 'app/assets/stylesheets/admin/all.css', " *= require admin/spree_burstnet\n", :before => /\*\//, :verbose => true
end
def add_migrations
run 'bundle exec rake railties:install:migrations FROM=spree_burstnet'
end
def run_migrations
run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]')
if run_migrations
run 'bundle exec rake db:migrate'
else
puts 'Skipping rake db:migrate, don\'t forget to run it!'
end
end
end
end
end

3
lib/spree_burstnet.rb Normal file
View File

@@ -0,0 +1,3 @@
require 'spree_core'
require 'spree_burstnet/engine'
require 'httparty'

View File

@@ -0,0 +1,22 @@
module SpreeBurstnet
class Engine < Rails::Engine
require 'spree/core'
isolate_namespace Spree
engine_name 'spree_burstnet'
config.autoload_paths += %W(#{config.root}/lib)
# use rspec for tests
config.generators do |g|
g.test_framework :rspec
end
def self.activate
Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c|
Rails.configuration.cache_classes ? require(c) : load(c)
end
end
config.to_prepare &method(:activate).to_proc
end
end

View File

@@ -0,0 +1,6 @@
FactoryGirl.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_burstnet/factories'
end

7
script/rails Normal file
View File

@@ -0,0 +1,7 @@
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
ENGINE_ROOT = File.expand_path('../..', __FILE__)
ENGINE_PATH = File.expand_path('../../lib/spree_burstnet/engine', __FILE__)
require 'rails/all'
require 'rails/engine/commands'

81
spec/spec_helper.rb Normal file
View File

@@ -0,0 +1,81 @@
# Run Coverage report
require 'simplecov'
SimpleCov.start do
add_group 'Controllers', 'app/controllers'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Models', 'app/models'
add_group 'Views', 'app/views'
add_group 'Libraries', 'lib'
end
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
require 'database_cleaner'
require 'ffaker'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f }
# Requires factories defined in spree_core
require 'spree/testing_support/factories'
require 'spree/testing_support/controller_requests'
require 'spree/testing_support/authorization_helpers'
require 'spree/testing_support/url_helpers'
# Requires factories defined in lib/spree_burstnet/factories.rb
require 'spree_burstnet/factories'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# == URL Helpers
#
# Allows access to Spree's routes in specs:
#
# visit spree.admin_path
# current_path.should eql(spree.products_path)
config.include Spree::TestingSupport::UrlHelpers
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
config.color = true
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner
# to cleanup after each test instead. Without transactional fixtures set to false the records created
# to setup a test will be unavailable to the browser, which runs under a seperate server instance.
config.use_transactional_fixtures = false
# Ensure Suite is set to use transactions for speed.
config.before :suite do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with :truncation
end
# Before each spec check if it is a Javascript test and switch between using database transactions or not where necessary.
config.before :each do
DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction
DatabaseCleaner.start
end
# After each spec clean the database.
config.after :each do
DatabaseCleaner.clean
end
config.fail_fast = ENV['FAIL_FAST'] || false
end

32
spree_burstnet.gemspec Normal file
View File

@@ -0,0 +1,32 @@
# encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_burstnet'
s.version = '2.0.0'
s.summary = 'BurstNet API implementation'
s.description = 'Allow a store to use BurstNet API to sell products'
s.required_ruby_version = '>= 1.9.3'
s.author = 'Dinis Lage'
s.email = 'dinis@lage.pw'
s.homepage = 'http://www.lage.pw'
#s.files = `git ls-files`.split("\n")
#s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 2.0.0'
s.add_dependency 'httparty'
s.add_development_dependency 'capybara', '~> 2.1'
s.add_development_dependency 'coffee-rails'
s.add_development_dependency 'database_cleaner'
s.add_development_dependency 'factory_girl', '~> 4.2'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.13'
s.add_development_dependency 'sass-rails'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end