Skip to content

Commit

Permalink
Add Import and Importable concerns
Browse files Browse the repository at this point in the history
The Import concern allows any controller to have import action that
invokes the import method of its model. Additionally we have a similar
concern in the routes as well.

The Importable concern allows any model to support import by providing
the importer class to be used. It expects the importer instance to
be initialized with some data and respond to import.
  • Loading branch information
namel3ss committed Oct 9, 2019
1 parent 1a38b1b commit 6fcf37b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
19 changes: 19 additions & 0 deletions app/controllers/concerns/import.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module Import
extend ActiveSupport::Concern

def import
if params[:file].nil?
flash[:error] = "No file was attached!"
else
begin
controller_name.classify.constantize.import(params[:file].read)
flash[:notice] = "Points were imported successfully!"
rescue ImportError => e
raise e
flash[:error] = e.message
end
end

redirect_to action: :index
end
end
1 change: 1 addition & 0 deletions app/errors/import_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
class ImportError < StandardError; end
13 changes: 13 additions & 0 deletions app/models/concerns/importable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Importable
extend ActiveSupport::Concern

class_methods do
def importer(importer_klass)
@importer_klass = importer_klass
end

def import(data)
@importer_klass.new(data).import
end
end
end
10 changes: 8 additions & 2 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
Rails.application.routes.draw do
concern :import do
collection do
post :import
end
end

namespace :admin do
resources :users
resources :speakers
Expand All @@ -8,8 +14,8 @@
root to: "users#index"
end

delete '/admin/places' => 'places#delete'
delete '/admin/stories' => 'stories#delete'
delete '/admin/places' => 'places#delete'
delete '/admin/stories' => 'stories#delete'

scope "(:locale)", locale: Regexp.union(I18n.available_locales.map(&:to_s)) do
resources :places do
Expand Down

0 comments on commit 6fcf37b

Please sign in to comment.