Fix RuboCop offenses

This commit is contained in:
Erik Michaels-Ober 2014-04-01 10:15:29 +02:00
parent 484633c63d
commit d4ad1a40f6
30 changed files with 87 additions and 91 deletions

View File

@ -1,6 +1,7 @@
--- ---
before_install: gem update bundler before_install: gem update bundler
before_script: bundle exec rake db:create db:schema:load before_script: bundle exec rake db:create db:schema:load
after_script: bundle exec rubocop -R
bundler_args: --without assets:development:production bundler_args: --without assets:development:production
language: ruby language: ruby
rvm: rvm:

View File

@ -3,10 +3,10 @@ class AddressesController < ApplicationController
def show def show
@address = Address.geocode("#{params[:address]}, #{params[:city_state]}") @address = Address.geocode("#{params[:address]}, #{params[:city_state]}")
unless @address.blank? if @address.blank?
respond_with @address render(json: {errors: {address: [t('errors.not_found', thing: t('defaults.address'))]}}, status: 404)
else else
render(json: {errors: {address: [t("errors.not_found", thing: t("defaults.address"))]}}, status: 404) respond_with @address
end end
end end
end end

View File

@ -2,8 +2,8 @@ class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception. # Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead. # For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception protect_from_forgery with: :exception
before_filter :set_flash_from_params before_action :set_flash_from_params
before_filter :set_locale before_action :set_locale
protected protected
@ -16,8 +16,8 @@ protected
end end
def set_locale def set_locale
available_languages = Dir.glob(Rails.root + "config/locales/??.yml").map do |file| available_languages = Dir.glob(Rails.root + 'config/locales/??.yml').collect do |file|
File.basename(file, ".yml") File.basename(file, '.yml')
end end
I18n.locale = http_accept_language.compatible_language_from(available_languages) || I18n.default_locale I18n.locale = http_accept_language.compatible_language_from(available_languages) || I18n.default_locale
end end

View File

@ -3,15 +3,15 @@ class InfoWindowController < ApplicationController
@thing = Thing.find_by_id(params[:thing_id]) @thing = Thing.find_by_id(params[:thing_id])
if @thing.adopted? if @thing.adopted?
if user_signed_in? && current_user == @thing.user if user_signed_in? && current_user == @thing.user
render("users/thank_you") render('users/thank_you')
else else
render("users/profile") render('users/profile')
end end
else else
if user_signed_in? if user_signed_in?
render("things/adopt") render('things/adopt')
else else
render("users/sign_in") render('users/sign_in')
end end
end end
end end

View File

@ -12,7 +12,7 @@ class PasswordsController < Devise::PasswordsController
def edit def edit
self.resource = resource_class.new self.resource = resource_class.new
resource.reset_password_token = params[:reset_password_token] resource.reset_password_token = params[:reset_password_token]
render("edit", layout: "info_window") render('edit', layout: 'info_window')
end end
def update def update
@ -22,7 +22,7 @@ class PasswordsController < Devise::PasswordsController
resource.unlock_access! if unlockable?(resource) resource.unlock_access! if unlockable?(resource)
sign_in(resource_name, resource) sign_in(resource_name, resource)
end end
redirect_to(controller: "main", action: "index") redirect_to(controller: 'main', action: 'index')
end end
private private

View File

@ -1,5 +1,5 @@
class SessionsController < Devise::SessionsController class SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token, only: [:destroy] skip_before_action :verify_authenticity_token, only: [:destroy]
def new def new
redirect_to(root_path) redirect_to(root_path)
@ -12,7 +12,7 @@ class SessionsController < Devise::SessionsController
yield resource if block_given? yield resource if block_given?
render(json: resource) render(json: resource)
else else
render(json: {errors: {password: [t("errors.password")]}}, status: 401) render(json: {errors: {password: [t('errors.password')]}}, status: 401)
end end
end end

View File

@ -3,10 +3,10 @@ class ThingsController < ApplicationController
def show def show
@things = Thing.find_closest(params[:lat], params[:lng], params[:limit] || 10) @things = Thing.find_closest(params[:lat], params[:lng], params[:limit] || 10)
unless @things.blank? if @things.blank?
respond_with @things render(json: {errors: {address: [t('errors.not_found', thing: t('defaults.thing'))]}}, status: 404)
else else
render(json: {errors: {address: [t("errors.not_found", thing: t("defaults.thing"))]}}, status: 404) respond_with @things
end end
end end

View File

@ -1,16 +1,15 @@
class UsersController < Devise::RegistrationsController class UsersController < Devise::RegistrationsController
def edit def edit
render("sidebar/edit_profile", layout: "sidebar") render('sidebar/edit_profile', layout: 'sidebar')
end end
def update def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if update_resource(resource, account_update_params) if update_resource(resource, account_update_params)
yield resource if block_given? yield resource if block_given?
sign_in(resource_name, resource, bypass: true) sign_in(resource_name, resource, bypass: true)
flash[:notice] = "Profile updated!" flash[:notice] = 'Profile updated!'
redirect_to(controller: "sidebar", action: "search") redirect_to(controller: 'sidebar', action: 'search')
else else
clean_up_passwords(resource) clean_up_passwords(resource)
render(json: {errors: resource.errors}, status: 500) render(json: {errors: resource.errors}, status: 500)
@ -38,5 +37,4 @@ private
def account_update_params def account_update_params
params.require(:user).permit(:address_1, :address_2, :city, :current_password, :email, :name, :organization, :password, :password_confirmation, :remember_me, :sms_number, :state, :voice_number, :zip) params.require(:user).permit(:address_1, :address_2, :city, :current_password, :email, :name, :organization, :password, :password_confirmation, :remember_me, :sms_number, :state, :voice_number, :zip)
end end
end end

View File

@ -1,5 +1,5 @@
module ApplicationHelper module ApplicationHelper
def us_states def us_states # rubocop:disable MethodLength
[ [
['Massachusetts', 'MA'], ['Massachusetts', 'MA'],
['Alabama', 'AL'], ['Alabama', 'AL'],

View File

@ -1,14 +1,9 @@
class ThingMailer < ActionMailer::Base class ThingMailer < ActionMailer::Base
default from: "adoptahydrant@cityofboston.gov" default from: 'adoptahydrant@cityofboston.gov'
def reminder(thing) def reminder(thing)
@thing = thing @thing = thing
@user = thing.user @user = thing.user
mail( mail(to: thing.user.email, subject: ['Remember to shovel', thing.name].compact.join(' '))
{
to: thing.user.email,
subject: ["Remember to shovel", thing.name].compact.join(' '),
}
)
end end
end end

View File

@ -2,6 +2,6 @@ class Address
include Geokit::Geocoders include Geokit::Geocoders
def self.geocode(address) def self.geocode(address)
MultiGeocoder.geocode(address).ll.split(',').map{|s| s.to_f} MultiGeocoder.geocode(address).ll.split(',').collect { |s| s.to_f }
end end
end end

View File

@ -1,7 +1,9 @@
class Reminder < ActiveRecord::Base class Reminder < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection include ActiveModel::ForbiddenAttributesProtection
validates_presence_of :from_user, :to_user, :thing belongs_to :from_user, class_name: 'User'
belongs_to :from_user, class_name: "User"
belongs_to :to_user, class_name: "User"
belongs_to :thing belongs_to :thing
belongs_to :to_user, class_name: 'User'
validates :from_user, presence: true
validates :thing, presence: true
validates :to_user, presence: true
end end

View File

@ -2,10 +2,11 @@ require 'geokit'
class Thing < ActiveRecord::Base class Thing < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection include ActiveModel::ForbiddenAttributesProtection
validates_uniqueness_of :city_id, allow_nil: true
validates_presence_of :lat, :lng
belongs_to :user belongs_to :user
has_many :reminders has_many :reminders
validates :city_id, uniqueness: true, allow_nil: true
validates :lat, presence: true
validates :lng, presence: true
def self.find_closest(lat, lng, limit = 10) def self.find_closest(lat, lng, limit = 10)
query = <<-SQL query = <<-SQL

View File

@ -1,21 +1,19 @@
class User < ActiveRecord::Base class User < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection include ActiveModel::ForbiddenAttributesProtection
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :validatable :trackable, :validatable
before_validation :remove_non_digits_from_phone_numbers
has_many :reminders_from, class_name: 'Reminder', foreign_key: 'from_user_id'
has_many :reminders_to, class_name: 'Reminder', foreign_key: 'to_user_id'
has_many :things
validates :name, presence: true
validates_formatting_of :email, using: :email validates_formatting_of :email, using: :email
validates_formatting_of :sms_number, using: :us_phone, allow_blank: true validates_formatting_of :sms_number, using: :us_phone, allow_blank: true
validates_formatting_of :voice_number, using: :us_phone, allow_blank: true validates_formatting_of :voice_number, using: :us_phone, allow_blank: true
validates_formatting_of :zip, using: :us_zip, allow_blank: true validates_formatting_of :zip, using: :us_zip, allow_blank: true
validates_presence_of :name
has_many :reminders_to, class_name: "Reminder", foreign_key: "to_user_id"
has_many :reminders_from, class_name: "Reminder", foreign_key: "from_user_id"
has_many :things
before_validation :remove_non_digits_from_phone_numbers
def remove_non_digits_from_phone_numbers def remove_non_digits_from_phone_numbers
self.sms_number = self.sms_number.to_s.gsub(/\D/, '').to_i if self.sms_number.present? self.sms_number = sms_number.to_s.gsub(/\D/, '').to_i if sms_number.present?
self.voice_number = self.voice_number.to_s.gsub(/\D/, '').to_i if self.voice_number.present? self.voice_number = voice_number.to_s.gsub(/\D/, '').to_i if voice_number.present?
end end
end end

View File

@ -1,4 +1,4 @@
# Set up gems listed in the Gemfile. # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])

View File

@ -82,8 +82,8 @@ AdoptAThing::Application.configure do
end end
ActionMailer::Base.smtp_settings = { ActionMailer::Base.smtp_settings = {
address: "smtp.sendgrid.net", address: 'smtp.sendgrid.net',
port: "25", port: '25',
authentication: :plain, authentication: :plain,
user_name: ENV['SENDGRID_USERNAME'], user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'], password: ENV['SENDGRID_PASSWORD'],

View File

@ -14,7 +14,7 @@ AdoptAThing::Application.configure do
# Configure static asset server for tests with Cache-Control for performance. # Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600" config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching. # Show full error reports and disable caching.
config.consider_all_requests_local = true config.consider_all_requests_local = true

View File

@ -95,7 +95,7 @@ Devise.setup do |config|
config.stretches = Rails.env.test? ? 1 : 10 config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password. # Setup a pepper to generate the encrypted password.
config.pepper = "d0ce05a602094357144e8d2ce90258904f8cb26fb943cefd6fe0b824752616a9254fadabed3a47ba5c0de66a359513768ab1ab233d9cfef893f376a9b5ebcf68" config.pepper = 'd0ce05a602094357144e8d2ce90258904f8cb26fb943cefd6fe0b824752616a9254fadabed3a47ba5c0de66a359513768ab1ab233d9cfef893f376a9b5ebcf68'
# ==> Configuration for :confirmable # ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without # A period that the user is allowed to access the website even without

View File

@ -1,5 +1,5 @@
RailsAdmin.config do |config| RailsAdmin.config do |config|
config.authenticate_with do config.authenticate_with do
redirect_to(main_app.root_path, flash: {warning: "You must be signed-in as an administrator to access that page"}) unless signed_in? && current_user.admin? redirect_to(main_app.root_path, flash: {warning: 'You must be signed-in as an administrator to access that page'}) unless signed_in? && current_user.admin?
end end
end end

View File

@ -8,7 +8,7 @@
# You can use `rake secret` to generate a secure secret key. # You can use `rake secret` to generate a secure secret key.
if Rails.env.production? && ENV['SECRET_TOKEN'].blank? if Rails.env.production? && ENV['SECRET_TOKEN'].blank?
raise 'The SECRET_TOKEN environment variable is not set.\n fail 'The SECRET_TOKEN environment variable is not set.\n
To generate it, run "rake secret", then set it with "heroku config:set SECRET_TOKEN=the_token_you_generated"' To generate it, run "rake secret", then set it with "heroku config:set SECRET_TOKEN=the_token_you_generated"'
end end

View File

@ -3,7 +3,7 @@ class AddDeviseToUsers < ActiveRecord::Migration
change_table(:users) do |t| change_table(:users) do |t|
## Database authenticatable ## Database authenticatable
# t.string :email, null: false, default: "" # t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: "" t.string :encrypted_password, null: false, default: ''
## Recoverable ## Recoverable
t.string :reset_password_token t.string :reset_password_token
@ -30,7 +30,6 @@ class AddDeviseToUsers < ActiveRecord::Migration
# t.string :unlock_token # Only if unlock strategy is :email or :both # t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at # t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model. # Uncomment below if timestamps were not included in your original model.
# t.timestamps # t.timestamps
end end
@ -44,6 +43,6 @@ class AddDeviseToUsers < ActiveRecord::Migration
def down def down
# By default, we don't want to make any assumption about how to roll back a migration when your # By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration. # model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration fail ActiveRecord::IrreversibleMigration
end end
end end

View File

@ -2,19 +2,19 @@ require 'test_helper'
class AddressesControllerTest < ActionController::TestCase class AddressesControllerTest < ActionController::TestCase
test 'should return latitude and longitude for a valid address' do test 'should return latitude and longitude for a valid address' do
stub_request(:get, "http://maps.google.com/maps/api/geocode/json"). stub_request(:get, 'http://maps.google.com/maps/api/geocode/json').
with(query: {address: "City Hall, Boston, MA", sensor: "false"}). with(query: {address: 'City Hall, Boston, MA', sensor: 'false'}).
to_return(body: File.read(File.expand_path('../../fixtures/city_hall.json', __FILE__))) to_return(body: File.read(File.expand_path('../../fixtures/city_hall.json', __FILE__)))
get :show, address: 'City Hall', city_state: "Boston, MA", format: 'json' get :show, address: 'City Hall', city_state: 'Boston, MA', format: 'json'
assert_not_nil assigns :address assert_not_nil assigns :address
end end
test 'should return an error for an invalid address' do test 'should return an error for an invalid address' do
stub_request(:get, "http://maps.google.com/maps/api/geocode/json"). stub_request(:get, 'http://maps.google.com/maps/api/geocode/json').
with(query: {address: ", ", sensor: "false"}). with(query: {address: ', ', sensor: 'false'}).
to_return(body: File.read(File.expand_path('../../fixtures/unknown_address.json', __FILE__))) to_return(body: File.read(File.expand_path('../../fixtures/unknown_address.json', __FILE__)))
stub_request(:get, "http://geocoder.us/service/csv/geocode"). stub_request(:get, 'http://geocoder.us/service/csv/geocode').
with(query: {address: ", "}). with(query: {address: ', '}).
to_return(body: File.read(File.expand_path('../../fixtures/unknown_address.json', __FILE__))) to_return(body: File.read(File.expand_path('../../fixtures/unknown_address.json', __FILE__)))
get :show, address: '', city_state: '', format: 'json' get :show, address: '', city_state: '', format: 'json'
assert_response :missing assert_response :missing

View File

@ -17,7 +17,7 @@ class InfoWindowControllerTest < ActionController::TestCase
assert_template 'users/thank_you' assert_template 'users/thank_you'
assert_select 'h2', 'Thank you for adopting this hydrant!' assert_select 'h2', 'Thank you for adopting this hydrant!'
assert_select 'form#abandon_form' do assert_select 'form#abandon_form' do
assert_select '[action=?]', "/things" assert_select '[action=?]', '/things'
assert_select '[method=?]', 'post' assert_select '[method=?]', 'post'
end end
assert_select 'input[name="_method"]' do assert_select 'input[name="_method"]' do
@ -48,7 +48,7 @@ class InfoWindowControllerTest < ActionController::TestCase
assert_template :adopt assert_template :adopt
assert_select 'h2', 'Adopt this Hydrant' assert_select 'h2', 'Adopt this Hydrant'
assert_select 'form#adoption_form' do assert_select 'form#adoption_form' do
assert_select '[action=?]', "/things" assert_select '[action=?]', '/things'
assert_select '[method=?]', 'post' assert_select '[method=?]', 'post'
end end
assert_select 'input[name="_method"]' do assert_select 'input[name="_method"]' do

View File

@ -4,7 +4,7 @@ class MainControllerTest < ActionController::TestCase
include Devise::TestHelpers include Devise::TestHelpers
setup do setup do
request.env["devise.mapping"] = Devise.mappings[:user] request.env['devise.mapping'] = Devise.mappings[:user]
@user = users(:erik) @user = users(:erik)
end end

View File

@ -3,7 +3,7 @@ require 'test_helper'
class PasswordsControllerTest < ActionController::TestCase class PasswordsControllerTest < ActionController::TestCase
include Devise::TestHelpers include Devise::TestHelpers
setup do setup do
request.env["devise.mapping"] = Devise.mappings[:user] request.env['devise.mapping'] = Devise.mappings[:user]
@user = users(:erik) @user = users(:erik)
end end

View File

@ -3,14 +3,14 @@ require 'test_helper'
class RemindersControllerTest < ActionController::TestCase class RemindersControllerTest < ActionController::TestCase
include Devise::TestHelpers include Devise::TestHelpers
setup do setup do
request.env["devise.mapping"] = Devise.mappings[:user] request.env['devise.mapping'] = Devise.mappings[:user]
@thing = things(:thing_1) @thing = things(:thing_1)
@dan = users(:dan) @dan = users(:dan)
@user = users(:erik) @user = users(:erik)
@thing.user = @dan @thing.user = @dan
@thing.save! @thing.save!
stub_request(:get, "http://maps.google.com/maps/api/geocode/json"). stub_request(:get, 'http://maps.google.com/maps/api/geocode/json').
with(query: {latlng: "42.383339,-71.049226", sensor: "false"}). with(query: {latlng: '42.383339,-71.049226', sensor: 'false'}).
to_return(body: File.read(File.expand_path('../../fixtures/city_hall.json', __FILE__))) to_return(body: File.read(File.expand_path('../../fixtures/city_hall.json', __FILE__)))
end end

View File

@ -3,7 +3,7 @@ require 'test_helper'
class SessionsControllerTest < ActionController::TestCase class SessionsControllerTest < ActionController::TestCase
include Devise::TestHelpers include Devise::TestHelpers
setup do setup do
request.env["devise.mapping"] = Devise.mappings[:user] request.env['devise.mapping'] = Devise.mappings[:user]
@user = users(:erik) @user = users(:erik)
end end
@ -31,7 +31,7 @@ class SessionsControllerTest < ActionController::TestCase
test 'should empty session on sign out' do test 'should empty session on sign out' do
sign_in @user sign_in @user
get :destroy, format: :json get :destroy, format: :json
assert_equal {}, session assert session.empty?
assert_response :success assert_response :success
end end
end end

View File

@ -3,7 +3,7 @@ require 'test_helper'
class UsersControllerTest < ActionController::TestCase class UsersControllerTest < ActionController::TestCase
include Devise::TestHelpers include Devise::TestHelpers
setup do setup do
request.env["devise.mapping"] = Devise.mappings[:user] request.env['devise.mapping'] = Devise.mappings[:user]
@user = users(:erik) @user = users(:erik)
end end

View File

@ -1,11 +1,11 @@
ENV["RAILS_ENV"] = "test" ENV['RAILS_ENV'] = 'test'
require 'simplecov' require 'simplecov'
require 'coveralls' require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter Coveralls::SimpleCov::Formatter,
] ]
SimpleCov.start('rails') SimpleCov.start('rails')
@ -13,7 +13,8 @@ require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help' require 'rails/test_help'
require 'webmock/minitest' require 'webmock/minitest'
class ActiveSupport::TestCase module ActiveSupport
class TestCase
ActiveRecord::Migration.check_pending! ActiveRecord::Migration.check_pending!
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
@ -24,3 +25,4 @@ class ActiveSupport::TestCase
# Add more helper methods to be used by all tests here... # Add more helper methods to be used by all tests here...
end end
end