Commit 7aa5e7cd by John Doe

moved to rails 5, added edit stream path

parent 7eb69eef
...@@ -2,7 +2,7 @@ source 'https://rubygems.org' ...@@ -2,7 +2,7 @@ source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.6' gem 'rails', '5.0.1'
# Use sqlite3 as the database for Active Record # Use sqlite3 as the database for Active Record
gem 'sqlite3' gem 'sqlite3'
# Use SCSS for stylesheets # Use SCSS for stylesheets
......
GEM GEM
remote: https://rubygems.org/ remote: https://rubygems.org/
specs: specs:
actionmailer (4.2.6) actioncable (5.0.1)
actionpack (= 4.2.6) actionpack (= 5.0.1)
actionview (= 4.2.6) nio4r (~> 1.2)
activejob (= 4.2.6) websocket-driver (~> 0.6.1)
actionmailer (5.0.1)
actionpack (= 5.0.1)
actionview (= 5.0.1)
activejob (= 5.0.1)
mail (~> 2.5, >= 2.5.4) mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 1.0, >= 1.0.5) rails-dom-testing (~> 2.0)
actionpack (4.2.6) actionpack (5.0.1)
actionview (= 4.2.6) actionview (= 5.0.1)
activesupport (= 4.2.6) activesupport (= 5.0.1)
rack (~> 1.6) rack (~> 2.0)
rack-test (~> 0.6.2) rack-test (~> 0.6.3)
rails-dom-testing (~> 1.0, >= 1.0.5) rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2) rails-html-sanitizer (~> 1.0, >= 1.0.2)
actionview (4.2.6) actionview (5.0.1)
activesupport (= 4.2.6) activesupport (= 5.0.1)
builder (~> 3.1) builder (~> 3.1)
erubis (~> 2.7.0) erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5) rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2) rails-html-sanitizer (~> 1.0, >= 1.0.2)
activejob (4.2.6) activejob (5.0.1)
activesupport (= 4.2.6) activesupport (= 5.0.1)
globalid (>= 0.3.0) globalid (>= 0.3.6)
activemodel (4.2.6) activemodel (5.0.1)
activesupport (= 4.2.6) activesupport (= 5.0.1)
builder (~> 3.1) activerecord (5.0.1)
activerecord (4.2.6) activemodel (= 5.0.1)
activemodel (= 4.2.6) activesupport (= 5.0.1)
activesupport (= 4.2.6) arel (~> 7.0)
arel (~> 6.0) activesupport (5.0.1)
activesupport (4.2.6) concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (~> 0.7) i18n (~> 0.7)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1) minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1) tzinfo (~> 1.1)
addressable (2.4.0) addressable (2.5.0)
arel (6.0.3) public_suffix (~> 2.0, >= 2.0.2)
arel (7.1.4)
ast (2.3.0) ast (2.3.0)
binding_of_caller (0.7.2) binding_of_caller (0.7.2)
debug_inspector (>= 0.0.1) debug_inspector (>= 0.0.1)
builder (3.2.2) builder (3.2.3)
byebug (9.0.5) byebug (9.0.6)
capybara (2.7.1) capybara (2.11.0)
addressable addressable
mime-types (>= 1.16) mime-types (>= 1.16)
nokogiri (>= 1.3.3) nokogiri (>= 1.3.3)
...@@ -57,8 +60,8 @@ GEM ...@@ -57,8 +60,8 @@ GEM
coffee-script (2.4.1) coffee-script (2.4.1)
coffee-script-source coffee-script-source
execjs execjs
coffee-script-source (1.10.0) coffee-script-source (1.12.2)
concurrent-ruby (1.0.2) concurrent-ruby (1.0.4)
crack (0.4.3) crack (0.4.3)
safe_yaml (~> 1.0.0) safe_yaml (~> 1.0.0)
cucumber (2.4.0) cucumber (2.4.0)
...@@ -71,28 +74,28 @@ GEM ...@@ -71,28 +74,28 @@ GEM
multi_test (>= 0.1.2) multi_test (>= 0.1.2)
cucumber-core (1.5.0) cucumber-core (1.5.0)
gherkin (~> 4.0) gherkin (~> 4.0)
cucumber-rails (1.4.4) cucumber-rails (1.4.5)
capybara (>= 1.1.2, < 3) capybara (>= 1.1.2, < 3)
cucumber (>= 1.3.8, < 3) cucumber (>= 1.3.8, < 4)
mime-types (>= 1.16, < 4) mime-types (>= 1.16, < 4)
nokogiri (~> 1.5) nokogiri (~> 1.5)
railties (>= 3, < 5.1) railties (>= 3, < 5.1)
cucumber-wire (0.0.1) cucumber-wire (0.0.1)
database_cleaner (1.5.3) database_cleaner (1.5.3)
debug_inspector (0.0.2) debug_inspector (0.0.2)
diff-lcs (1.2.5) diff-lcs (1.3)
docile (1.1.5) docile (1.1.5)
erubis (2.7.0) erubis (2.7.0)
execjs (2.7.0) execjs (2.7.0)
factory_girl (4.7.0) factory_girl (4.8.0)
activesupport (>= 3.0.0) activesupport (>= 3.0.0)
factory_girl_rails (4.7.0) factory_girl_rails (4.8.0)
factory_girl (~> 4.7.0) factory_girl (~> 4.8.0)
railties (>= 3.0.0) railties (>= 3.0.0)
faker (1.6.6) faker (1.7.2)
i18n (~> 0.5) i18n (~> 0.5)
ffi (1.9.14) ffi (1.9.17)
ffi (1.9.14-x64-mingw32) ffi (1.9.17-x64-mingw32)
formatador (0.2.5) formatador (0.2.5)
gherkin (4.0.0) gherkin (4.0.0)
globalid (0.3.7) globalid (0.3.7)
...@@ -114,25 +117,25 @@ GEM ...@@ -114,25 +117,25 @@ GEM
guard-rubocop (1.2.0) guard-rubocop (1.2.0)
guard (~> 2.0) guard (~> 2.0)
rubocop (~> 0.20) rubocop (~> 0.20)
hashdiff (0.3.0) hashdiff (0.3.2)
httparty (0.14.0) httparty (0.14.0)
multi_xml (>= 0.5.2) multi_xml (>= 0.5.2)
i18n (0.7.0) i18n (0.7.0)
jbuilder (2.6.0) jbuilder (2.6.1)
activesupport (>= 3.0.0, < 5.1) activesupport (>= 3.0.0, < 5.1)
multi_json (~> 1.2) multi_json (~> 1.2)
jquery-rails (4.1.1) jquery-rails (4.2.2)
rails-dom-testing (>= 1, < 3) rails-dom-testing (>= 1, < 3)
railties (>= 4.2.0) railties (>= 4.2.0)
thor (>= 0.14, < 2.0) thor (>= 0.14, < 2.0)
json (1.8.3) json (1.8.6)
listen (3.1.5) listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4) rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7) rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2) ruby_dep (~> 1.2)
loofah (2.0.3) loofah (2.0.3)
nokogiri (>= 1.5.9) nokogiri (>= 1.5.9)
lumberjack (1.0.10) lumberjack (1.0.11)
mail (2.6.4) mail (2.6.4)
mime-types (>= 1.16, < 4) mime-types (>= 1.16, < 4)
method_source (0.8.2) method_source (0.8.2)
...@@ -140,77 +143,74 @@ GEM ...@@ -140,77 +143,74 @@ GEM
mime-types-data (~> 3.2015) mime-types-data (~> 3.2015)
mime-types-data (3.2016.0521) mime-types-data (3.2016.0521)
mini_portile2 (2.1.0) mini_portile2 (2.1.0)
minitest (5.9.0) minitest (5.10.1)
multi_json (1.12.1) multi_json (1.12.1)
multi_test (0.1.2) multi_test (0.1.2)
multi_xml (0.5.5) multi_xml (0.6.0)
nenv (0.3.0) nenv (0.3.0)
nokogiri (1.6.8) nio4r (1.2.1)
nokogiri (1.7.0.1)
mini_portile2 (~> 2.1.0) mini_portile2 (~> 2.1.0)
pkg-config (~> 1.1.7) nokogiri (1.7.0.1-x64-mingw32)
nokogiri (1.6.8-x64-mingw32)
mini_portile2 (~> 2.1.0) mini_portile2 (~> 2.1.0)
pkg-config (~> 1.1.7)
notiffany (0.1.1) notiffany (0.1.1)
nenv (~> 0.1) nenv (~> 0.1)
shellany (~> 0.0) shellany (~> 0.0)
parser (2.3.1.2) parser (2.3.3.1)
ast (~> 2.2) ast (~> 2.2)
pkg-config (1.1.7)
powerpack (0.1.1) powerpack (0.1.1)
pry (0.10.4) pry (0.10.4)
coderay (~> 1.1.0) coderay (~> 1.1.0)
method_source (~> 0.8.1) method_source (~> 0.8.1)
slop (~> 3.4) slop (~> 3.4)
rack (1.6.4) public_suffix (2.0.5)
rack (2.0.1)
rack-cors (0.4.0) rack-cors (0.4.0)
rack-test (0.6.3) rack-test (0.6.3)
rack (>= 1.0) rack (>= 1.0)
rails (4.2.6) rails (5.0.1)
actionmailer (= 4.2.6) actioncable (= 5.0.1)
actionpack (= 4.2.6) actionmailer (= 5.0.1)
actionview (= 4.2.6) actionpack (= 5.0.1)
activejob (= 4.2.6) actionview (= 5.0.1)
activemodel (= 4.2.6) activejob (= 5.0.1)
activerecord (= 4.2.6) activemodel (= 5.0.1)
activesupport (= 4.2.6) activerecord (= 5.0.1)
activesupport (= 5.0.1)
bundler (>= 1.3.0, < 2.0) bundler (>= 1.3.0, < 2.0)
railties (= 4.2.6) railties (= 5.0.1)
sprockets-rails sprockets-rails (>= 2.0.0)
rails-deprecated_sanitizer (1.0.3) rails-dom-testing (2.0.2)
activesupport (>= 4.2.0.alpha) activesupport (>= 4.2.0, < 6.0)
rails-dom-testing (1.0.7) nokogiri (~> 1.6)
activesupport (>= 4.2.0.beta, < 5.0)
nokogiri (~> 1.6.0)
rails-deprecated_sanitizer (>= 1.0.1)
rails-html-sanitizer (1.0.3) rails-html-sanitizer (1.0.3)
loofah (~> 2.0) loofah (~> 2.0)
railties (4.2.6) railties (5.0.1)
actionpack (= 4.2.6) actionpack (= 5.0.1)
activesupport (= 4.2.6) activesupport (= 5.0.1)
method_source
rake (>= 0.8.7) rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0) thor (>= 0.18.1, < 2.0)
rainbow (2.1.0) rainbow (2.2.1)
rake (11.2.2) rake (12.0.0)
rb-fsevent (0.9.7) rb-fsevent (0.9.8)
rb-inotify (0.9.7) rb-inotify (0.9.7)
ffi (>= 0.5.0) ffi (>= 0.5.0)
rdoc (4.2.2) rdoc (4.3.0)
json (~> 1.4)
rspec (3.5.0) rspec (3.5.0)
rspec-core (~> 3.5.0) rspec-core (~> 3.5.0)
rspec-expectations (~> 3.5.0) rspec-expectations (~> 3.5.0)
rspec-mocks (~> 3.5.0) rspec-mocks (~> 3.5.0)
rspec-core (3.5.2) rspec-core (3.5.4)
rspec-support (~> 3.5.0) rspec-support (~> 3.5.0)
rspec-expectations (3.5.0) rspec-expectations (3.5.0)
diff-lcs (>= 1.2.0, < 2.0) diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.5.0) rspec-support (~> 3.5.0)
rspec-json_expectations (1.4.0) rspec-json_expectations (2.1.0)
rspec-mocks (3.5.0) rspec-mocks (3.5.0)
diff-lcs (>= 1.2.0, < 2.0) diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.5.0) rspec-support (~> 3.5.0)
rspec-rails (3.5.1) rspec-rails (3.5.2)
actionpack (>= 3.0) actionpack (>= 3.0)
activesupport (>= 3.0) activesupport (>= 3.0)
railties (>= 3.0) railties (>= 3.0)
...@@ -219,23 +219,23 @@ GEM ...@@ -219,23 +219,23 @@ GEM
rspec-mocks (~> 3.5.0) rspec-mocks (~> 3.5.0)
rspec-support (~> 3.5.0) rspec-support (~> 3.5.0)
rspec-support (3.5.0) rspec-support (3.5.0)
rubocop (0.42.0) rubocop (0.47.1)
parser (>= 2.3.1.1, < 3.0) parser (>= 2.3.3.1, < 3.0)
powerpack (~> 0.1) powerpack (~> 0.1)
rainbow (>= 1.99.1, < 3.0) rainbow (>= 1.99.1, < 3.0)
ruby-progressbar (~> 1.7) ruby-progressbar (~> 1.7)
unicode-display_width (~> 1.0, >= 1.0.1) unicode-display_width (~> 1.0, >= 1.0.1)
ruby-progressbar (1.8.1) ruby-progressbar (1.8.1)
ruby_dep (1.4.0) ruby_dep (1.5.0)
safe_yaml (1.0.4) safe_yaml (1.0.4)
sass (3.4.22) sass (3.4.23)
sass-rails (5.0.6) sass-rails (5.0.6)
railties (>= 4.0.0, < 6) railties (>= 4.0.0, < 6)
sass (~> 3.1) sass (~> 3.1)
sprockets (>= 2.8, < 4.0) sprockets (>= 2.8, < 4.0)
sprockets-rails (>= 2.0, < 4.0) sprockets-rails (>= 2.0, < 4.0)
tilt (>= 1.1, < 3) tilt (>= 1.1, < 3)
sdoc (0.4.1) sdoc (0.4.2)
json (~> 1.7, >= 1.7.7) json (~> 1.7, >= 1.7.7)
rdoc (~> 4.0) rdoc (~> 4.0)
shellany (0.0.1) shellany (0.0.1)
...@@ -245,21 +245,22 @@ GEM ...@@ -245,21 +245,22 @@ GEM
simplecov-html (~> 0.10.0) simplecov-html (~> 0.10.0)
simplecov-html (0.10.0) simplecov-html (0.10.0)
slop (3.6.0) slop (3.6.0)
spring (1.7.2) spring (2.0.1)
activesupport (>= 4.2)
spring-commands-rspec (1.0.4) spring-commands-rspec (1.0.4)
spring (>= 0.9.1) spring (>= 0.9.1)
sprockets (3.7.0) sprockets (3.7.1)
concurrent-ruby (~> 1.0) concurrent-ruby (~> 1.0)
rack (> 1, < 3) rack (> 1, < 3)
sprockets-rails (3.1.1) sprockets-rails (3.2.0)
actionpack (>= 4.0) actionpack (>= 4.0)
activesupport (>= 4.0) activesupport (>= 4.0)
sprockets (>= 3.0.0) sprockets (>= 3.0.0)
sqlite3 (1.3.11) sqlite3 (1.3.13)
sqlite3 (1.3.11-x64-mingw32) sqlite3 (1.3.13-x64-mingw32)
terminal-notifier (1.6.3) terminal-notifier (1.7.1)
terminal-notifier-guard (1.7.0) terminal-notifier-guard (1.7.0)
thor (0.19.1) thor (0.19.4)
thread_safe (0.3.5) thread_safe (0.3.5)
tilt (2.0.5) tilt (2.0.5)
turbolinks (5.0.1) turbolinks (5.0.1)
...@@ -267,21 +268,24 @@ GEM ...@@ -267,21 +268,24 @@ GEM
turbolinks-source (5.0.0) turbolinks-source (5.0.0)
tzinfo (1.2.2) tzinfo (1.2.2)
thread_safe (~> 0.1) thread_safe (~> 0.1)
tzinfo-data (1.2016.6) tzinfo-data (1.2016.10)
tzinfo (>= 1.0.0) tzinfo (>= 1.0.0)
uglifier (3.0.1) uglifier (3.0.4)
execjs (>= 0.3.0, < 3) execjs (>= 0.3.0, < 3)
unicode-display_width (1.1.0) unicode-display_width (1.1.3)
vcr (3.0.3) vcr (3.0.3)
web-console (2.3.0) web-console (2.3.0)
activemodel (>= 4.0) activemodel (>= 4.0)
binding_of_caller (>= 0.7.2) binding_of_caller (>= 0.7.2)
railties (>= 4.0) railties (>= 4.0)
sprockets-rails (>= 2.0, < 4.0) sprockets-rails (>= 2.0, < 4.0)
webmock (2.1.0) webmock (2.3.2)
addressable (>= 2.3.6) addressable (>= 2.3.6)
crack (>= 0.3.2) crack (>= 0.3.2)
hashdiff hashdiff
websocket-driver (0.6.4)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.2)
xpath (2.0.0) xpath (2.0.0)
nokogiri (~> 1.3) nokogiri (~> 1.3)
...@@ -303,7 +307,7 @@ DEPENDENCIES ...@@ -303,7 +307,7 @@ DEPENDENCIES
jbuilder (~> 2.0) jbuilder (~> 2.0)
jquery-rails jquery-rails
rack-cors rack-cors
rails (= 4.2.6) rails (= 5.0.1)
rspec-json_expectations rspec-json_expectations
rspec-rails (~> 3.1) rspec-rails (~> 3.1)
rubocop rubocop
......
...@@ -37,17 +37,27 @@ class DbAdapter ...@@ -37,17 +37,27 @@ class DbAdapter
end end
def set_folder_metadata(db_folder) def set_folder_metadata(db_folder)
params = { path: "#{db_folder.path}/info", _set_path_metadata("#{db_folder.path}/info",
data: __build_folder_metadata(db_folder) }.to_json __build_folder_metadata(db_folder))
end
def set_stream_metadata(db_stream)
_set_path_metadata(db_stream.path,
__build_stream_metadata(db_stream))
end
def _set_path_metadata(path, data)
params = { path: path,
data: data }.to_json
response = self.class.post("#{@url}/stream/update_metadata", response = self.class.post("#{@url}/stream/update_metadata",
body: params, body: params,
headers: { 'Content-Type' => 'application/json' }) headers: { 'Content-Type' => 'application/json' })
if response.code != 200 if response.code != 200
Rails.logger.warn ( Rails.logger.warn
"#{@url}: update_metadata(#{db_folder.path})"+ "#{@url}: update_metadata(#{path})"\
" => #{response.code}:#{response.body}" " => #{response.code}:#{response.body}"
)
return { error: true, msg: "error updating #{db_folder.path} metadata" } return { error: true, msg: "error updating #{path} metadata" }
end end
{ error: false, msg: 'success' } { error: false, msg: 'success' }
end end
...@@ -58,7 +68,18 @@ class DbAdapter ...@@ -58,7 +68,18 @@ class DbAdapter
.slice('name', 'description', 'hidden') .slice('name', 'description', 'hidden')
.to_json .to_json
{ config_key__: attribs }.to_json { config_key__: attribs }.to_json
end end
# convert folder attributes to __config_key json
def __build_stream_metadata(db_stream)
attribs = db_stream.attributes
.slice('name', 'name_abbrev', 'description', 'hidden')
# elements are called streams in the nilmdb metadata
# and they don't have id or timestamp fields
attribs[:streams] = db_stream.db_elements.map {|e|
e.attributes.except("id","created_at","updated_at","db_stream_id")}
{ config_key__: attribs.to_json }.to_json
end
# retrieve metadata for a particular stream # retrieve metadata for a particular stream
def __get_metadata(path) def __get_metadata(path)
......
...@@ -12,7 +12,7 @@ class DbFoldersController < ApplicationController ...@@ -12,7 +12,7 @@ class DbFoldersController < ApplicationController
folder = DbFolder.find(params[:id]) folder = DbFolder.find(params[:id])
adapter = DbAdapter.new(folder.db.url) adapter = DbAdapter.new(folder.db.url)
service = EditFolder.new(adapter) service = EditFolder.new(adapter)
service.run(folder, folder_params.symbolize_keys) service.run(folder, folder_params)
if(service.success?) if(service.success?)
render json: folder, shallow: false render json: folder, shallow: false
else else
......
# frozen_string_literal: true # frozen_string_literal: true
# Controller for DbFiles # Controller for DbStreams
class DbStreamsController < ApplicationController class DbStreamsController < ApplicationController
def update
stream = DbStream.find(params[:id])
adapter = DbAdapter.new(stream.db.url)
service = EditStream.new(adapter)
service.run(stream, stream_params.symbolize_keys)
if(service.success?)
render json: stream
else
render json: service, status: :unprocessable_entity
end
end
private
def stream_params
params.permit(:name, :description, :hidden, :name_abbrev, :elements)
end
end end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
# frozen_string_literal: true # frozen_string_literal: true
# Database object # Database object
class Db < ActiveRecord::Base class Db < ApplicationRecord
belongs_to :root_folder, belongs_to :root_folder,
foreign_key: 'db_folder_id', foreign_key: 'db_folder_id',
class_name: 'DbFolder', class_name: 'DbFolder',
......
# frozen_string_literal: true # frozen_string_literal: true
# Decimation level of a file # Decimation level of a file
class DbDecimation < ActiveRecord::Base class DbDecimation < ApplicationRecord
belongs_to :db_stream belongs_to :db_stream
def as_json(_options = {}) def as_json(_options = {})
......
...@@ -2,9 +2,14 @@ ...@@ -2,9 +2,14 @@
# a column in a stream, this is the lowest element # a column in a stream, this is the lowest element
# in the db hierarchy and contains actual data # in the db hierarchy and contains actual data
class DbElement < ActiveRecord::Base class DbElement < ApplicationRecord
belongs_to :db_stream belongs_to :db_stream
validates :name, presence: true
validates :name, uniqueness: { scope: :db_stream_id,
message: ' is already used in this folder'}
def as_json(_options = {}) def as_json(_options = {})
super(except: [:created_at, :updated_at]) super(except: [:created_at, :updated_at])
end end
......
# frozen_string_literal: true # frozen_string_literal: true
# a folder in the database, may contain one or more DbFiles as files # a folder in the database, may contain one or more DbFiles as files
# and one or more DbFolders as subfolders # and one or more DbFolders as subfolders
class DbFolder < ActiveRecord::Base class DbFolder < ApplicationRecord
belongs_to :parent, class_name: 'DbFolder' belongs_to :parent, class_name: 'DbFolder'
belongs_to :db belongs_to :db
...@@ -15,18 +17,13 @@ class DbFolder < ActiveRecord::Base ...@@ -15,18 +17,13 @@ class DbFolder < ActiveRecord::Base
dependent: :destroy dependent: :destroy
validates_presence_of :name validates_presence_of :name
validate :name_is_unique_in_group # validates_with DbFolderValidator
validates :name, uniqueness: { scope: :parent_id,
message: ' is already used in this folder'}
#:section: Utility Methods #:section: Utility Methods
#vaildator to ensure the name is unique to the parent.
def name_is_unique_in_group
self.parent.subfolders.each do |folder|
if((folder.name == self.name) and (folder.id != self.id ))
self.errors.add(:name, "[#{self.name}] is already used")
end
end
end
def self.defined_attributes def self.defined_attributes
......
...@@ -15,12 +15,16 @@ class DbDataTypeValidator < ActiveModel::Validator ...@@ -15,12 +15,16 @@ class DbDataTypeValidator < ActiveModel::Validator
end end
# A file in the database, contains one or more Streams # A file in the database, contains one or more Streams
class DbStream < ActiveRecord::Base class DbStream < ApplicationRecord
belongs_to :db_folder belongs_to :db_folder
belongs_to :db belongs_to :db
has_many :db_elements, dependent: :destroy, autosave: true
has_many :db_elements, dependent: :destroy
has_many :db_decimations, dependent: :destroy has_many :db_decimations, dependent: :destroy
accepts_nested_attributes_for :db_elements
validates :name, presence: true
validates :name, uniqueness: { scope: :db_folder_id,
message: ' is already used in this folder'}
validates_with DbDataTypeValidator validates_with DbDataTypeValidator
......
# frozen_string_literal: true # frozen_string_literal: true
# NILM object # NILM object
class Nilm < ActiveRecord::Base class Nilm < ApplicationRecord
has_one :db has_one :db
def as_json(_options = {}) def as_json(_options = {})
......
...@@ -9,7 +9,7 @@ class EditFolder ...@@ -9,7 +9,7 @@ class EditFolder
@db_adapter = db_adapter @db_adapter = db_adapter
end end
def run(db_folder, **attribs) def run(db_folder, attribs)
# only accept valid attributes # only accept valid attributes
attribs.slice!(:name, :description, :hidden) attribs.slice!(:name, :description, :hidden)
# assign the new attributes and check if the # assign the new attributes and check if the
...@@ -17,8 +17,8 @@ class EditFolder ...@@ -17,8 +17,8 @@ class EditFolder
db_folder.assign_attributes(attribs) db_folder.assign_attributes(attribs)
unless db_folder.valid? unless db_folder.valid?
db_folder.errors db_folder.errors
.full_messages .full_messages
.each{|e| add_error(e)} .each { |e| add_error(e) }
return self return self
end end
# local model checks out, update the remote NilmDB # local model checks out, update the remote NilmDB
......
# frozen_string_literal: true
# Handles changing DbStream attributes
class EditStream
include ServiceStatus
def initialize(db_adapter)
super()
@db_adapter = db_adapter
end
def run(db_stream, attribs)
# only accept valid attributes
stream_attribs = attribs.slice(:name, :description,
:hidden, :name_abbrev)
begin
stream_attribs[:db_elements_attributes] =
__parse_element_attribs(attribs[:elements])
rescue TypeError
add_error("invalid db_elements_attributes parameter")
return self
end
# assign the new attributes and check if the
# result is valid (eg elements can't have the same name)
db_stream.assign_attributes(stream_attribs)
unless db_stream.valid?
db_stream.errors
.full_messages
.each { |e| add_error(e) }
return self
end
# local model checks out, update the remote NilmDB
status = @db_adapter.set_stream_metadata(db_stream)
# if there was an error don't save the model
if status[:error]
add_error(status[:msg])
return self
end
# everything went well, save the model
db_stream.save
self
end
def __parse_element_attribs(attribs)
if !attribs.nil? && attribs.length>=1
attribs.map { |element|
{id: element[:id],
name: element[:name]}
}
else
[]
end
end
end
...@@ -42,7 +42,7 @@ module ServiceStatus ...@@ -42,7 +42,7 @@ module ServiceStatus
end end
def success? def success?
!self.warnings? && !self.errors? !warnings? && !errors?
end end
def run def run
...@@ -64,7 +64,7 @@ module ServiceStatus ...@@ -64,7 +64,7 @@ module ServiceStatus
def as_json(_options = {}) def as_json(_options = {})
{ {
errors: @errors, errors: @errors,
warnings: @warnings warnings: @warnings
} }
end end
end end
#!/usr/bin/env ruby #!/usr/bin/env ruby
begin APP_PATH = File.expand_path('../config/application', __dir__)
load File.expand_path('../spring', __FILE__)
rescue LoadError => e
raise unless e.message.include?('spring')
end
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot' require_relative '../config/boot'
require 'rails/commands' require 'rails/commands'
#!/usr/bin/env ruby #!/usr/bin/env ruby
begin
load File.expand_path('../spring', __FILE__)
rescue LoadError => e
raise unless e.message.include?('spring')
end
require_relative '../config/boot' require_relative '../config/boot'
require 'rake' require 'rake'
Rake.application.run Rake.application.run
#!/usr/bin/env ruby #!/usr/bin/env ruby
require 'pathname' require 'pathname'
require 'fileutils'
include FileUtils
# path to your application root. # path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
Dir.chdir APP_ROOT do def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==")
end
chdir APP_ROOT do
# This script is a starting point to setup your application. # This script is a starting point to setup your application.
# Add necessary setup steps to this file: # Add necessary setup steps to this file.
puts "== Installing dependencies ==" puts '== Installing dependencies =='
system "gem install bundler --conservative" system! 'gem install bundler --conservative'
system "bundle check || bundle install" system('bundle check') || system!('bundle install')
# puts "\n== Copying sample files ==" # puts "\n== Copying sample files =="
# unless File.exist?("config/database.yml") # unless File.exist?('config/database.yml')
# system "cp config/database.yml.sample config/database.yml" # cp 'config/database.yml.sample', 'config/database.yml'
# end # end
puts "\n== Preparing database ==" puts "\n== Preparing database =="
system "bin/rake db:setup" system! 'bin/rails db:setup'
puts "\n== Removing old logs and tempfiles ==" puts "\n== Removing old logs and tempfiles =="
system "rm -f log/*" system! 'bin/rails log:clear tmp:clear'
system "rm -rf tmp/cache"
puts "\n== Restarting application server ==" puts "\n== Restarting application server =="
system "touch tmp/restart.txt" system! 'bin/rails restart'
end end
#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
include FileUtils
# path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
def system!(*args)
system(*args) || abort("\n== Command #{args} failed ==")
end
chdir APP_ROOT do
# This script is a way to update your development environment automatically.
# Add necessary update steps to this file.
puts '== Installing dependencies =='
system! 'gem install bundler --conservative'
system('bundle check') || system!('bundle install')
puts "\n== Updating database =="
system! 'bin/rails db:migrate'
puts "\n== Removing old logs and tempfiles =="
system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
system! 'bin/rails restart'
end
# frozen_string_literal: true require_relative 'boot'
require File.expand_path('../boot', __FILE__)
require 'rails/all' require 'rails/all'
...@@ -12,18 +11,6 @@ module ControlPanel ...@@ -12,18 +11,6 @@ module ControlPanel
# Settings in config/environments/* take precedence over those specified here. # Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers # Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded. # -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Add folders under the services directory # Add folders under the services directory
%w(nilm db db_folder db_stream).each do |service| %w(nilm db db_folder db_stream).each do |service|
config.autoload_paths << Rails.root.join("app/services/#{service}") config.autoload_paths << Rails.root.join("app/services/#{service}")
......
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile. require 'bundler/setup' # Set up gems listed in the Gemfile.
development:
adapter: async
test:
adapter: async
production:
adapter: redis
url: redis://localhost:6379/1
# Load the Rails application. # Load the Rails application.
require File.expand_path('../application', __FILE__) require_relative 'application'
# Initialize the Rails application. # Initialize the Rails application.
Rails.application.initialize! Rails.application.initialize!
...@@ -9,13 +9,28 @@ Rails.application.configure do ...@@ -9,13 +9,28 @@ Rails.application.configure do
# Do not eager load code on boot. # Do not eager load code on boot.
config.eager_load = false config.eager_load = false
# Show full error reports and disable caching. # Show full error reports.
config.consider_all_requests_local = true config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send. # Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger. # Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log config.active_support.deprecation = :log
...@@ -27,19 +42,15 @@ Rails.application.configure do ...@@ -27,19 +42,15 @@ Rails.application.configure do
# number of complex assets. # number of complex assets.
config.assets.debug = true config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets, # Suppress logger output for asset requests.
# yet still be able to expire them through the digest params. config.assets.quiet = true
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations # Raises error for missing translations
# config.action_view.raise_on_missing_translations = true # config.action_view.raise_on_missing_translations = true
# allow cross origin requests # Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.middleware.insert_before 0, Rack::Cors do config.middleware.insert_before 0, Rack::Cors do
allow do allow do
origins '*' origins '*'
......
...@@ -14,15 +14,9 @@ Rails.application.configure do ...@@ -14,15 +14,9 @@ Rails.application.configure do
config.consider_all_requests_local = false config.consider_all_requests_local = false
config.action_controller.perform_caching = true config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since # Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this. # Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS. # Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier config.assets.js_compressor = :uglifier
...@@ -31,16 +25,20 @@ Rails.application.configure do ...@@ -31,16 +25,20 @@ Rails.application.configure do
# Do not fallback to assets pipeline if a precompiled asset is missed. # Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false config.assets.compile = false
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files. # Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true # config.force_ssl = true
...@@ -49,16 +47,15 @@ Rails.application.configure do ...@@ -49,16 +47,15 @@ Rails.application.configure do
config.log_level = :debug config.log_level = :debug
# Prepend all log lines with the following tags. # Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ] config.log_tags = [ :request_id ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production. # Use a different cache store in production.
# config.cache_store = :mem_cache_store # config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server. # Use a real queuing backend for Active Job (and separate queues per environment)
# config.action_controller.asset_host = 'http://assets.example.com' # config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "control_panel_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors. # Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors.
...@@ -74,6 +71,16 @@ Rails.application.configure do ...@@ -74,6 +71,16 @@ Rails.application.configure do
# Use default logging formatter so that PID and timestamp are not suppressed. # Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations. # Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false config.active_record.dump_schema_after_migration = false
end end
...@@ -12,9 +12,11 @@ Rails.application.configure do ...@@ -12,9 +12,11 @@ Rails.application.configure do
# preloads Rails for running tests, you may have to set it to true. # preloads Rails for running tests, you may have to set it to true.
config.eager_load = false config.eager_load = false
# Configure static file server for tests with Cache-Control for performance. # Configure public file server for tests with Cache-Control for performance.
config.serve_static_files = true config.public_file_server.enabled = true
config.static_cache_control = 'public, max-age=3600' config.public_file_server.headers = {
'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
...@@ -25,15 +27,13 @@ Rails.application.configure do ...@@ -25,15 +27,13 @@ Rails.application.configure do
# Disable request forgery protection in test environment. # Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world. # Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the # The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array. # ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr. # Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr config.active_support.deprecation = :stderr
......
# Be sure to restart your server when you modify this file.
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
# Be sure to restart your server when you modify this file. # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json Rails.application.config.action_dispatch.cookies_serializer = :json
# Be sure to restart your server when you modify this file.
#
# This file contains migration options to ease your Rails 5.0 upgrade.
#
# Once upgraded flip defaults one by one to migrate to the new default.
#
# Read the Guide for Upgrading Ruby on Rails for more info on each option.
# Enable per-form CSRF tokens. Previous versions had false.
Rails.application.config.action_controller.per_form_csrf_tokens = false
# Enable origin-checking CSRF mitigation. Previous versions had false.
Rails.application.config.action_controller.forgery_protection_origin_check = false
# Make Ruby 2.4 preserve the timezone of the receiver when calling `to_time`.
# Previous versions had false.
ActiveSupport.to_time_preserves_timezone = false
# Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = false
# Do not halt callback chains when a callback returns false. Previous versions had true.
ActiveSupport.halt_callback_chains_on_return_false = true
# Be sure to restart your server when you modify this file. # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_ControlPanel_session' Rails.application.config.session_store :cookie_store, key: '_control_panel_session'
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters) wrap_parameters format: [:json]
end end
# To enable root element in JSON for ActiveRecord objects. # To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do # ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true # self.include_root_in_json = true
# end # end
# Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!
# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
# on_worker_boot do
# ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
# end
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
...@@ -5,58 +5,4 @@ Rails.application.routes.draw do ...@@ -5,58 +5,4 @@ Rails.application.routes.draw do
resources :db_streams resources :db_streams
resources :db_files resources :db_files
resources :db_folders resources :db_folders
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end end
...@@ -5,16 +5,16 @@ ...@@ -5,16 +5,16 @@
# Make sure the secret is at least 30 characters and all random, # Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks. # no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key. # You can use `rails secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private # Make sure the secrets in this file are kept private
# if you're sharing your code publicly. # if you're sharing your code publicly.
development: development:
secret_key_base: f1b2e6830a9791623ed6435dc6a893c2061c25476b94fde01f74a8af69577838aa2c455ceecf7f2b2242abb3b1965b1b50b6a35adc9155a90799c3b685e33a49 secret_key_base: fab2042587cdf751633b04a5b9ee9d35b6e3f7e6d58072dbf7522943b41b7ec38485a0dd393727e9f8a99cec0c0c38e846d21e9eaf4def9e585ca7c599750086
test: test:
secret_key_base: a93a665ffc8f0913c5167bb22b9427b3c208dd4aa002ca2ee8ce0614fb7a06c8af84c62c7b5d345c8673e57745b0ea6a0a2d13adaa4216814a37476e59d73dca secret_key_base: 54f457fa59508035f7b585741602a1a674b98dd52f7e7365cfd599381d48a95c1b27e8ab397dc7dbaf2fa34a8cb7c1f970b59ec7fff0c9a080c6a3ba4a68cf66
# Do not keep production secrets in the repository, # Do not keep production secrets in the repository,
# instead read values from the environment. # instead read values from the environment.
......
%w(
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
).each { |path| Spring.watch(path) }
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to # of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition. # incrementally modify your database, and then regenerate this schema definition.
......
...@@ -15,6 +15,25 @@ describe DbAdapter do ...@@ -15,6 +15,25 @@ describe DbAdapter do
) )
end end
end end
describe 'set_stream_metadata' do
it 'updates config_key in metadata', :vcr do
adapter = DbAdapter.new(url)
stream = DbStream.new(path: '/tutorial/pump-events',
name: 'test', description: 'new', db_elements_attributes: [
{column: 0, name: 'element1'},{column: 1, name: 'element2'}])
result = adapter.set_stream_metadata(stream)
expect(result[:error]).to be false
end
it 'returns error on server failure', :vcr do
adapter = DbAdapter.new(url)
stream = DbStream.new(path: '/badpath')
result = adapter.set_stream_metadata(stream)
expect(result[:error]).to be true
expect(result[:msg]).to match(/badpath/)
end
end
describe 'set_folder_metadata' do describe 'set_folder_metadata' do
it 'updates config_key in metadata', :vcr do it 'updates config_key in metadata', :vcr do
adapter = DbAdapter.new(url) adapter = DbAdapter.new(url)
......
...@@ -6,7 +6,7 @@ RSpec.describe DbsController, type: :controller do ...@@ -6,7 +6,7 @@ RSpec.describe DbsController, type: :controller do
describe 'GET show' do describe 'GET show' do
it 'lists the database contents' do it 'lists the database contents' do
allow(Db).to receive(:find).and_return(Db.new) allow(Db).to receive(:find).and_return(Db.new)
get :show, id: 1 get :show, params: { id: 1}
expect(Db).to have_received(:find) expect(Db).to have_received(:find)
expect(response.header['Content-Type']).to include('application/json') expect(response.header['Content-Type']).to include('application/json')
end end
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
# generic DbStream # generic DbStream
FactoryGirl.define do FactoryGirl.define do
factory :db_stream do factory :db_element do
name { Faker::Lorem.word } name { Faker::Lorem.word }
end end
end end
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
# generic DbStream # generic DbStream
FactoryGirl.define do FactoryGirl.define do
factory :db_file do factory :db_stream do
name { Faker::Lorem.word } name { Faker::Lorem.word }
data_type {"float32_1"}
end end
end end
...@@ -14,4 +14,25 @@ RSpec.describe 'DbElement' do ...@@ -14,4 +14,25 @@ RSpec.describe 'DbElement' do
specify { expect(db_element).to respond_to(:plottable) } specify { expect(db_element).to respond_to(:plottable) }
specify { expect(db_element).to respond_to(:discrete) } specify { expect(db_element).to respond_to(:discrete) }
end end
describe 'validation' do
it 'forbids an empty name' do
element = DbElement.new(name: '')
element.validate
expect(element.errors[:name].any?).to be true
end
it 'name is unique in stream' do
stream = DbStream.create(name: 'parent')
elem1 = DbElement.create(name: 'shared', db_stream: stream)
elem2 = DbElement.new(name: 'shared', db_stream: stream)
elem2.validate
expect(elem2.errors[:name].any?).to be true
# but if element is in a different stream its ok
stream2 = DbStream.create(name: 'other_parent')
stream2.db_elements << elem2
elem2.validate
expect(elem2.errors[:name].any?).to be false
end
end
end end
...@@ -16,9 +16,6 @@ RSpec.describe 'DbFolder' do ...@@ -16,9 +16,6 @@ RSpec.describe 'DbFolder' do
specify { expect(db_folder).to respond_to(:subfolders) } specify { expect(db_folder).to respond_to(:subfolders) }
specify { expect(db_folder).to respond_to(:db_streams) } specify { expect(db_folder).to respond_to(:db_streams) }
specify { expect(db_folder).to respond_to(:db) } specify { expect(db_folder).to respond_to(:db) }
end end
describe 'when destroyed' do describe 'when destroyed' do
...@@ -54,5 +51,11 @@ RSpec.describe 'DbFolder' do ...@@ -54,5 +51,11 @@ RSpec.describe 'DbFolder' do
db_folder.name = '' db_folder.name = ''
expect(db_folder.valid?).to be false expect(db_folder.valid?).to be false
end end
it 'name is unique in parent' do
parent = DbFolder.create(name: 'parent')
child1 = DbFolder.create(name: 'shared', parent: parent)
child2 = DbFolder.new(name: 'shared', parent: parent)
expect(child2.valid?).to be false
end
end end
end end
...@@ -17,6 +17,30 @@ RSpec.describe 'DbStream' do ...@@ -17,6 +17,30 @@ RSpec.describe 'DbStream' do
end end
describe 'validation' do
it 'requires a name' do
stream = DbStream.new(name: '')
stream.validate
expect(stream.errors[:name].any?).to be true
end
it 'requires a unique name' do
folder = DbFolder.create(name: 'parent')
DbStream.create(name: 'stream', db_folder: folder)
stream2 = DbStream.new(name: 'stream', db_folder: folder)
stream2.validate
expect(stream2.errors[:name].any?).to be true
end
end
describe 'update' do
it 'saves attributes to child elements' do
stream = DbStream.create(name: 'stream', hidden: false)
element = DbElement.create(name: 'A', db_stream: stream)
new_attrs = {db_elements_attributes: [{id: element.id, units: 'new'}]}
stream.assign_attributes(new_attrs)
expect(stream.db_elements.first.units).to eq('new')
end
end
describe 'child elements' do describe 'child elements' do
it 'are destroyed with parent stream' do it 'are destroyed with parent stream' do
element = DbElement.create element = DbElement.create
......
# frozen_string_literal: true
require 'rails_helper'
describe 'EditStream service' do
let(:db_adapter) { instance_double(DbAdapter) }
let(:stream) { FactoryGirl.create(:db_stream, path: '/stream/path', name: 'old') }
let(:element) { DbElement.create(name: 'elem', db_stream: stream)}
let(:service) { EditStream.new(db_adapter) }
# db adapter return values
let(:success) { { error: false, msg: '' } }
let(:error) { { error: true, msg: 'server error' } }
it 'changes stream and element attributes' do
attribs = { id: 0, invalid_attrib: 'ignore',
name: 'new name', name_abbrev: 'nn',
elements: [{id: element.id, name: 'new!'}] }
allow(db_adapter).to receive(:set_stream_metadata).and_return(success)
# run the service, it should call the adapter and save the folder
service.run(stream, attribs)
expect(db_adapter).to have_received(:set_stream_metadata).with(stream)
expect(stream.name).to eq('new name')
expect(stream.name_abbrev).to eq('nn')
expect(DbElement.find(element.id).name).to eq('new!')
end
it 'checks to make sure new attributes are valid' do
attribs = { name: '' } # cannot have empty name
allow(db_adapter).to receive(:set_stream_metadata).and_return(success)
# run the service, it shouldn't call the database adapter
service.run(stream, attribs)
expect(service.errors?).to be true
expect(db_adapter).to_not have_received(:set_stream_metadata)
end
it 'does not change stream or elements on a server error' do
attribs = { name: 'new', elements: [{id: element.id, name: 'new'}]}
allow(db_adapter).to receive(:set_stream_metadata).and_return(error)
allow(stream).to receive(:save!)
allow(element).to receive(:save!)
# run the service, it shouldn't save the folder object
service.run(stream, attribs)
expect(service.errors?).to be true
expect(stream).to_not have_received(:save!)
expect(element).to_not have_received(:save!)
end
it 'produces error for invalid parameter structure' do
attribs = {name: 'new', elements: {id: 0, name: 'nice try'}}
allow(db_adapter).to receive(:set_stream_metadata).and_return(success)
# run the service, it shouldn't call the database adapter
service.run(stream, attribs)
expect(service.errors?).to be true
expect(db_adapter).to_not have_received(:set_stream_metadata)
end
end
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'InsertStream' do
describe 'insert_stream' do
# mock the DbService and DbBuilder
let(:db_service) { double(create_stream: true) }
let(:db_builder) { double(build_path: '/test/file') }
# a stream to insert
let(:new_stream) { FactoryGirl.build_stubbed(:db_stream) }
# a folder to insert it in
let(:parent_folder) { FactoryGirl.build_stubbed(:db_folder) }
it 'adds the given stream to the folder' do
stream_inserter = InsertStream.new(db_service: db_service,
db_builder: db_builder)
stream_inserter.insert_stream(folder: parent_folder, stream: new_stream)
expect(new_stream.db_folder).to eq(parent_folder)
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment