Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
AllCops:
Exclude:
- 'bin/*'
- 'config/**/*'
- 'db/**/*'
- 'vendor/bundle/**/*'
- '**/Gemfile'
- '**/Rakefile'
- 'spec/spec_helper.rb'
- 'spec/rails_helper.rb'
- 'spec/support/**/*'
- 'node_modules/**/*'
- 'app/views/**/*'

Rails:
Enabled: true

Naming/VariableNumber:
EnforcedStyle: 'snake_case'

Layout/SpaceInsideHashLiteralBraces:
EnforcedStyle: no_space

Style/Documentation:
Enabled: false

Metrics/BlockLength:
Exclude:
- 'spec/**/*.rb'

Metrics/LineLength:
Max: 105

Metrics/MethodLength:
Max: 20

Style/Lambda:
EnforcedStyle: literal
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ gem 'jbuilder', '~> 2.5'
gem 'haml', '~> 5.0', '>= 5.0.4'
gem 'bootstrap', '~> 4.1.3'
gem 'jquery-rails'
gem 'rubocop', require: false

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍
It'd be nice to move it to development, :test group though


group :development, :test do
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
Expand Down
26 changes: 19 additions & 7 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ GEM
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
arel (8.0.0)
ast (2.4.0)
autoprefixer-rails (9.1.4)
execjs
bindex (0.5.0)
Expand Down Expand Up @@ -72,11 +73,6 @@ GEM
diff-lcs (1.3)
erubi (1.7.1)
execjs (2.7.0)
factory_bot (4.11.1)
activesupport (>= 3.0.0)
factory_bot_rails (4.11.1)
factory_bot (~> 4.11.1)
railties (>= 3.0.0)
ffi (1.9.25)
globalid (0.4.1)
activesupport (>= 4.2.0)
Expand All @@ -85,6 +81,7 @@ GEM
tilt
i18n (1.1.0)
concurrent-ruby (~> 1.0)
jaro_winkler (1.5.1)
jbuilder (2.7.0)
activesupport (>= 4.2.0)
multi_json (>= 1.2)
Expand All @@ -109,8 +106,12 @@ GEM
nio4r (2.3.1)
nokogiri (1.8.5)
mini_portile2 (~> 2.3.0)
parallel (1.12.1)
parser (2.5.3.0)
ast (~> 2.4.0)
pg (1.1.3)
popper_js (1.14.3)
powerpack (0.1.2)
public_suffix (3.0.3)
puma (3.12.0)
rack (2.0.5)
Expand Down Expand Up @@ -139,6 +140,7 @@ GEM
method_source
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
rainbow (3.0.0)
rake (12.3.1)
rb-fsevent (0.10.3)
rb-inotify (0.9.10)
Expand All @@ -160,6 +162,15 @@ GEM
rspec-mocks (~> 3.8.0)
rspec-support (~> 3.8.0)
rspec-support (3.8.0)
rubocop (0.60.0)
jaro_winkler (~> 1.5.1)
parallel (~> 1.10)
parser (>= 2.5, != 2.5.1.1)
powerpack (~> 0.1)
rainbow (>= 2.2.2, < 4.0)
ruby-progressbar (~> 1.7)
unicode-display_width (~> 1.4.0)
ruby-progressbar (1.10.0)
ruby_dep (1.5.0)
rubyzip (1.2.2)
sass (3.6.0)
Expand Down Expand Up @@ -201,6 +212,7 @@ GEM
thread_safe (~> 0.1)
uglifier (4.1.19)
execjs (>= 0.3.0, < 3)
unicode-display_width (1.4.0)
web-console (3.7.0)
actionview (>= 5.0)
activemodel (>= 5.0)
Expand All @@ -221,7 +233,6 @@ DEPENDENCIES
capybara (~> 2.13)
coffee-rails (~> 4.2)
database_cleaner
factory_bot_rails (~> 4.0)
haml (~> 5.0, >= 5.0.4)
jbuilder (~> 2.5)
jquery-rails
Expand All @@ -230,6 +241,7 @@ DEPENDENCIES
puma (~> 3.7)
rails (~> 5.1.6)
rspec-rails (~> 3.5)
rubocop
sass-rails (~> 5.0)
selenium-webdriver
shoulda-matchers (~> 3.1)
Expand All @@ -241,4 +253,4 @@ DEPENDENCIES
web-console (>= 3.3.0)

BUNDLED WITH
1.16.5
1.17.1
24 changes: 8 additions & 16 deletions app/controllers/urls_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,20 @@ def new
end

def create
@url = Url.new(url_params)
@url.clean_url
@url = CreateShortUrlService.new(url_params).call

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a matter of preference but I'd consider the usage of Callable module / class so that this line could be rewritten like CreateShortUrlService.call(url_params)


if @url.new_link?
if @url.save
render js: "document.getElementById('short_url_box').classList
.remove('d-none');document.getElementById('short_url')
.innerText='http://#{request.host}/#{@url.url_short}/';"
else
flash[:alert] = @url.errors.full_messages
redirect_to :root
end
else
@url_in_database = Url.find_by_url_clean(@url.url_clean)
if @url.save
render js: "document.getElementById('short_url_box').classList
.remove('d-none');document.getElementById('short_url')
.innerText='http://#{request.host}/#{@url_in_database.url_short}/';"
.remove('d-none');document.getElementById('short_url')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rendering of JS code from controllers is considered to be a bad practice since essentially you are mixing responsibilities and it makes the code harder to maintain, extend and reason about.
https://reinteractive.com/posts/195-rails-server-sent-javascript-considered-harmful

.innerText='http://#{request.host}/#{@url.url_short}/';"
else
flash[:alert] = @url.errors.full_messages
redirect_to :root
end
end

def show
@url = Url.find_by_url_short(params[:url_short])
@url = Url.find_by(url_short: params[:url_short])
redirect_to "http://#{@url.url_clean}/"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if @url is nil?
You can either use find_by!(notice the !) in combination with rescue_from ActiveRecord::RecordNotFound or manually handle it by checking whether the @url is present beforehand

end

Expand Down
24 changes: 24 additions & 0 deletions app/models/concerns/links_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module LinksGenerator
extend ActiveSupport::Concern

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather use Ruby self.included, self.extended hooks as opposed to Concerns but that's debatable so feel free to read on the topic and decide for yourself 🙂


def new_link?
find_url_clean_duplicate.nil?
end

def find_url_clean_duplicate
Url.find_by(url_clean: url_clean)
end

def clean_url
clean_url = url_orginal.strip
clean_url = clean_url.downcase.gsub(%r{(https?:\/\/)|(www\.)}, '')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's advisable to move regexes to the constant

clean_url.slice!(-1) if clean_url[-1] == '/'
self.url_clean = clean_url

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concerns and modules that rely on the presence of some attributes or external methods indicate that those aren't the appropriate abstractions for this problem. Ideally concerns / modules should be independent on the class they are included in, otherwise it's just a fancy way to split the code between different files

end

def generate_short_url
short_url = generate_string_url(8)
short_url = generate_string_url(8) until Url.find_by(url_short: generate_string_url(8)).nil?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while Url.exists?(url_short: ...) should be faster

self.url_short = short_url
end
end
24 changes: 1 addition & 23 deletions app/models/url.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,9 @@
class Url < ApplicationRecord
include CharsArray
include LinksGenerator

validates :url_orginal, presence: true
validates :url_orginal, url: true

before_create :generate_short_url

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an indication of a bad architecture since you're using a method defined in a module as a callback on the model therefore it's easily breakable by excluding the module


def new_link?
find_duplicate.nil?
end

def find_duplicate
Url.find_by_url_clean(url_clean)
end

def clean_url
clean_url = url_orginal.strip
clean_url = clean_url.downcase.gsub(/(https?:\/\/)|(www\.)/, '')
clean_url.slice!(-1) if clean_url[-1] == '/'
self.url_clean = clean_url
end

def generate_short_url
short_url = generate_string_url(8)
until Url.find_by_url_short(generate_string_url(8)).nil?
short_url = generate_string_url(8)
end
self.url_short = short_url
end
end
15 changes: 15 additions & 0 deletions app/services/create_short_url_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class CreateShortUrlService
def initialize(params)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using params = {} as a fallback in case no arguments are provided

@url_orginal = params[:url_orginal]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using private attr_reader for encapsulation & increased flexibility

end

def call
@url = Url.new(url_orginal: @url_orginal)
@url.clean_url
if @url.new_link?
@url
else
Url.find_by(url_clean: @url.url_clean)
end
end
end
20 changes: 12 additions & 8 deletions app/validators/url_validator.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "must be a valid URL") unless url_valid?(value)
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || 'must be a valid URL') unless url_valid?(value)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's considered a good practice to move static strings to a constants. Also - don't forget to freeze it(freeze or #frozen_string_literal: true at the top of the file) to prevent unnecessary memory allocation

end

def url_valid?(url)
begin
url = URI.parse(url)
rescue URI::InvalidURIError
false
end

def url_valid?(url)
url = URI.parse(url) rescue false
url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS)
end
end
url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
end
end
24 changes: 24 additions & 0 deletions spec/controllers/url_controller_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
require 'rails_helper'

RSpec.describe UrlsController do

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I remember there's no need to use RSpec.describe as opposed to simply describe here

describe 'POST create' do
let(:valid_params) { {'url' => {'url_orginal' => 'http://wkostanski.pl'}} }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using FactoryBot & Faker instead of hard-coded params

let(:invalid_params) { {'url' => {'url_orginal' => 'wkostanski.pl'}} }
it 'with valid params' do

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Empty line before each it is missing

expect do
post :create, params: valid_params

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is duplicated across 3 tests therefore you can reduce the duplication by moving it to a subject, e.g

subject { post :create, params: valid_params }

it 'something' do
  expect(subject).to change(....)
end

end.to change(Url, :count).by(1)
end
it 'with invalid params' do
expect do
post :create, params: invalid_params
end.to change(Url, :count).by(0)
end
it 'with duplicated params' do
post :create, params: valid_params
expect do
post :create, params: valid_params
end.to change(Url, :count).by(0)
end
end
end