Skip to content

Commit

Permalink
Merge pull request #285 from interagent/rubocop-template
Browse files Browse the repository at this point in the history
Add and apply rubocop to template
  • Loading branch information
gudmundur authored Jan 6, 2017
2 parents fa9296a + 52b1f9d commit cff6bc8
Show file tree
Hide file tree
Showing 25 changed files with 126 additions and 80 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
Gemfile.lock
.bundle
.ruby-*
.tags
29 changes: 29 additions & 0 deletions lib/template/.rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
require:
- rubocop-rspec
AllCops:
TargetRubyVersion: 2.3
# Offense count: 8
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives.
# URISchemes: http, https
Metrics/LineLength:
Enabled: false

# Offense count: 1
# Configuration parameters: Max.
RSpec/ExampleLength:
Enabled: false

# Offense count: 1
Style/ClassVars:
Enabled: false

# Offense count: 6
Style/Documentation:
Enabled: false

Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes

Style/FrozenStringLiteralComment:
Enabled: false
4 changes: 3 additions & 1 deletion lib/template/Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ gem "sucker_punch"

group :development, :test do
gem "pry-byebug"
gem "rubocop", "~> 0.46.0", require: false
gem "rubocop-rspec", require: false
end

group :test do
gem "simplecov", require: false
gem "committee"
gem "database_cleaner"
gem "dotenv"
gem "rack-test"
gem "rspec"
gem "simplecov", require: false
end
3 changes: 2 additions & 1 deletion lib/template/Rakefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@

require "pliny/tasks"

# Add your rake tasks to lib/tasks!
Dir["./lib/tasks/*.rake"].each { |task| load task }

task :default => :spec
task default: :spec
14 changes: 7 additions & 7 deletions lib/template/bin/console
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env ruby

require_relative '../lib/application'
require_relative "../lib/application"

def basic_prompt(target_self, nest_level, pry)
# override DEPLOYMENT to identify console sessions (eg: staging/production/etc)
Expand All @@ -9,13 +9,13 @@ def basic_prompt(target_self, nest_level, pry)
end

Pry.prompt = [
proc { |target_self, nest_level, pry|
basic_prompt(target_self, nest_level, pry) + "> "
},
proc do |target_self, nest_level, pry|
basic_prompt(target_self, nest_level, pry) + "> "
end,

proc { |target_self, nest_level, pry|
basic_prompt(target_self, nest_level, pry) + "* "
}
proc do |target_self, nest_level, pry|
basic_prompt(target_self, nest_level, pry) + "* "
end
]

Pry.start
4 changes: 3 additions & 1 deletion lib/template/bin/run
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env ruby

require_relative '../lib/application'
# rubocop:disable Lint/Eval

require_relative "../lib/application"

eval ARGV.join(" ")
2 changes: 1 addition & 1 deletion lib/template/config.ru
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require_relative 'lib/application'
require_relative "lib/application"

$stdout.sync = true
$stderr.sync = true
Expand Down
4 changes: 2 additions & 2 deletions lib/template/config/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ module Config
# Override -- value is returned or the set default.
override :database_timeout, 10, int
override :db_pool, 5, int
override :deployment, 'production', string
override :deployment, "production", string
override :force_ssl, true, bool
override :app_env, 'production', string
override :app_env, "production", string
override :port, 5000, int
override :pretty_json, false, bool
override :puma_max_threads, 16, int
Expand Down
6 changes: 3 additions & 3 deletions lib/template/config/initializers/database.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
database_setup_proc = lambda do |conn|
# identify postgres connections coming from this process in pg_stat_activity
process_identifier = ENV["DYNO"] || File.basename($0).gsub(/\W+/, "_")
process_identifier = ENV["DYNO"] || File.basename($PROGRAM_NAME).gsub(/\W+/, "_")
conn.execute "SET statement_timeout = '#{Config.database_timeout}s'"
conn.execute "SET application_name = '#{process_identifier}'"
end

DB = Sequel.connect(Config.database_url,
max_connections: Config.db_pool,
after_connect: database_setup_proc)
max_connections: Config.db_pool,
after_connect: database_setup_proc)
7 changes: 3 additions & 4 deletions lib/template/config/initializers/rollbar.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
require 'pliny/error_reporters/rollbar'
require "pliny/error_reporters/rollbar"

Pliny::ErrorReporters.error_reporters << Pliny::ErrorReporters::Rollbar

Rollbar.configure do |config|
config.enabled = ENV.has_key?('ROLLBAR_ACCESS_TOKEN')
config.enabled = ENV.key?("ROLLBAR_ACCESS_TOKEN")
config.disable_rack_monkey_patch = true
config.access_token = ENV["ROLLBAR_ACCESS_TOKEN"]
config.environment = ENV['ROLLBAR_ENV']
config.environment = ENV["ROLLBAR_ENV"]
config.logger = Pliny::RollbarLogger.new
config.use_sucker_punch
end

2 changes: 1 addition & 1 deletion lib/template/config/puma.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

on_worker_boot do
# force Sequel's thread pool to be refreshed
Sequel::DATABASES.each { |db| db.disconnect }
Sequel::DATABASES.each(&:disconnect)
end

preload_app!
Expand Down
4 changes: 2 additions & 2 deletions lib/template/lib/application.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'bundler'
require "bundler"
Bundler.require

require_relative 'initializer'
require_relative "initializer"
10 changes: 5 additions & 5 deletions lib/template/lib/endpoints/health.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
module Endpoints
class Health < Base
namespace '/health' do
namespace "/health" do
get do
encode({})
end

get '/db' do
get "/db" do
database?
database_available?
encode({})
Expand All @@ -14,14 +14,14 @@ class Health < Base
private

def database?
fail Pliny::Errors::NotFound if DB.nil?
raise Pliny::Errors::NotFound if DB.nil?
end

def database_available?
fail Pliny::Errors::ServiceUnavailable unless DB.test_connection
raise Pliny::Errors::ServiceUnavailable unless DB.test_connection
rescue Sequel::Error => e
message = e.message.strip
Pliny.log(db: true, health: true, at: 'exception', message: message)
Pliny.log(db: true, health: true, at: "exception", message: message)
raise Pliny::Errors::ServiceUnavailable
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/template/lib/endpoints/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ class Schema < Base
get "/schema.json" do
content_type "application/schema+json"
headers["Cache-Control"] = "public, max-age=3600"
unless File.exists?(schema_filename)
unless File.exist?(schema_filename)
message = "This application does not have a schema file."
raise Pliny::Errors::NotFound.new(message)
raise Pliny::Errors::NotFound, message
end
File.read(schema_filename)
end
Expand Down
2 changes: 1 addition & 1 deletion lib/template/lib/mediators/base.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module Mediators
class Base
def self.run(options={})
def self.run(options = {})
new(options).call
end
end
Expand Down
14 changes: 9 additions & 5 deletions lib/template/lib/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@
use Pliny::Middleware::Metrics
use Pliny::Middleware::Instruments
use Pliny::Middleware::RescueErrors, raise: Config.raise_errors?
use Rack::Timeout,
service_timeout: Config.timeout if Config.timeout > 0
use Pliny::Middleware::Versioning,
default: Config.versioning_default,
app_name: Config.versioning_app_name if Config.versioning?
if Config.timeout.positive?
use Rack::Timeout,
service_timeout: Config.timeout
end
if Config.versioning?
use Pliny::Middleware::Versioning,
default: Config.versioning_default,
app_name: Config.versioning_app_name
end
use Rack::Deflater
use Rack::MethodOverride
use Rack::SSL if Config.force_ssl?
Expand Down
5 changes: 2 additions & 3 deletions lib/template/lib/serializers/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,21 @@ class Base
@@structures = {}

def self.structure(type, &blk)
@@structures["#{self.name}::#{type}"] = blk
@@structures["#{name}::#{type}"] = blk
end

def initialize(type)
@type = type
end

def serialize(object)
object.respond_to?(:map) ? object.map{|item| serializer.call(item)} : serializer.call(object)
object.respond_to?(:map) ? object.map { |item| serializer.call(item) } : serializer.call(object)
end

private

def serializer
@@structures["#{self.class.name}::#{@type}"]
end

end
end
6 changes: 6 additions & 0 deletions lib/template/lib/tasks/rubocop.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

require "rubocop/rake_task"

RuboCop::RakeTask.new do |task|
task.requires << "rubocop-rspec"
end
6 changes: 4 additions & 2 deletions lib/template/lib/tasks/spec.rake
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@

# define our own version of the spec task because rspec might not be available
# in the production environment, so we can't rely on RSpec::Core::RakeTask
desc "Run all app specs"
task :spec do
require "rspec/core"
code = RSpec::Core::Runner.run(
["./spec"],
$stderr, $stdout)
exit(code) unless code == 0
$stderr, $stdout
)
exit(code) unless code.zero?
end
32 changes: 16 additions & 16 deletions lib/template/spec/endpoints/health_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,48 @@ def app
Endpoints::Health
end

describe 'GET /health' do
it 'returns a 200' do
get '/health'
describe "GET /health" do
it "returns a 200" do
get "/health"
assert_equal(200, last_response.status)
assert_equal('application/json;charset=utf-8', last_response.headers['Content-Type'])
assert_equal(2, last_response.headers['Content-Length'].to_i)
assert_equal("application/json;charset=utf-8", last_response.headers["Content-Type"])
assert_equal(2, last_response.headers["Content-Length"].to_i)
assert_equal({}, MultiJson.decode(last_response.body))
end
end

describe 'GET /health/db' do
it 'raises a 404 when no database is available' do
describe "GET /health/db" do
it "raises a 404 when no database is available" do
allow(DB).to receive(:nil?).and_return(true)

assert_raises Pliny::Errors::NotFound do
get '/health/db'
get "/health/db"
end
end

it 'raises a 503 on Sequel exceptions' do
it "raises a 503 on Sequel exceptions" do
allow(DB).to receive(:test_connection).and_raise(Sequel::Error)

assert_raises Pliny::Errors::ServiceUnavailable do
get '/health/db'
get "/health/db"
end
end

it 'raises a 503 when connection testing fails' do
it "raises a 503 when connection testing fails" do
allow(DB).to receive(:test_connection).and_return(false)

assert_raises Pliny::Errors::ServiceUnavailable do
get '/health/db'
get "/health/db"
end
end

it 'returns a 200' do
it "returns a 200" do
allow(DB).to receive(:test_connection).and_return(true)

get '/health/db'
get "/health/db"
assert_equal(200, last_response.status)
assert_equal('application/json;charset=utf-8', last_response.headers['Content-Type'])
assert_equal(2, last_response.headers['Content-Length'].to_i)
assert_equal("application/json;charset=utf-8", last_response.headers["Content-Type"])
assert_equal(2, last_response.headers["Content-Length"].to_i)
assert_equal({}, MultiJson.decode(last_response.body))
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/template/spec/endpoints/schema_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
RSpec.describe Endpoints::Schema do
include Rack::Test::Methods

let(:schema_filename) { "#{Config.root}/schema/schema.json" }

subject(:get_schema) { get "/schema.json" }

let(:schema_filename) { "#{Config.root}/schema/schema.json" }

context "without a schema.json" do
before do
allow(File).to receive(:exists?).and_return(false)
Expand Down
8 changes: 4 additions & 4 deletions lib/template/spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
require "bundler"
require "dotenv"
Bundler.require(:default, :test)
Dotenv.load('.env.test')
Dotenv.load(".env.test")

# Get only App Config first, to avoid pulling in libraries until
# spec_support has a chance to run, which is important for at least
Expand All @@ -29,7 +29,7 @@
end

config.before :all do
load('db/seeds.rb') if File.exist?('db/seeds.rb')
load("db/seeds.rb") if File.exist?("db/seeds.rb")
end

config.before :each do
Expand All @@ -49,10 +49,10 @@
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
config.order = "random"

# the rack app to be tested with rack-test:
def app
@rack_app || fail("Missing @rack_app")
@rack_app || raise("Missing @rack_app")
end
end
Loading

0 comments on commit cff6bc8

Please sign in to comment.