diff --git a/.env.template b/.env.template index 7a2c28c3a2..d5a5ac7cf1 100644 --- a/.env.template +++ b/.env.template @@ -26,7 +26,7 @@ ENJU_LEAF_EXTRACT_TEXT= ENJU_LEAF_EXTRACT_FILESIZE_LIMIT=2097152 # ENJU_LEAF_RESOURCESYNC_BASE_URL=http://localhost:8080 -CANTALOUPE_BASE_URI=http://cantaloupe:8182 +CANTALOUPE_BASE_URL=http://localhost:8182 NODE_OPTIONS=--openssl-legacy-provider diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 4d57e52d9e..7b9f982e8a 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -14,24 +14,32 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: docker/metadata-action@v4 + - uses: docker/metadata-action@v5 id: meta with: - images: ghcr.io/next-l/enju_leaf + images: | + enju_leaf tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}} type=semver,pattern={{major}}.{{minor}} - - name: Docker Login - uses: docker/login-action@v2 + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Login to GitHub Container Registry + uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push Docker images - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v6 with: push: true - tags: ${{ steps.meta.outputs.tags }} + tags: | + projectnextl/${{ steps.meta.outputs.tags }} + ghcr.io/next-l/${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 88e53db6c1..9adc542456 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -28,14 +28,14 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Setup Pages - uses: actions/configure-pages@v3 + uses: actions/configure-pages@v5 - name: Build with Jekyll uses: actions/jekyll-build-pages@v1 with: source: ./docs destination: ./_site - name: Upload artifact - uses: actions/upload-pages-artifact@v1 + uses: actions/upload-pages-artifact@v3 # Deployment job deploy: @@ -47,4 +47,4 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v2 + uses: actions/deploy-pages@v4 diff --git a/.github/workflows/rubyonrails.yml b/.github/workflows/rubyonrails.yml index f11c038227..8f63a9a9c5 100644 --- a/.github/workflows/rubyonrails.yml +++ b/.github/workflows/rubyonrails.yml @@ -18,10 +18,6 @@ jobs: POSTGRES_DB: enju_leaf_test POSTGRES_USER: rails POSTGRES_PASSWORD: password - redis: - image: redis:6 - ports: - - "6379:6379" env: RAILS_ENV: test ENJU_LEAF_BIND_ADDRESS: 127.0.0.1 diff --git a/.rubocop.yml b/.rubocop.yml index 8cefdb3c0a..f9d86d4a54 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,62 +1,8 @@ -require: rubocop-rails +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } -Rails: - Enabled: true -AllCops: - TargetRubyVersion: 2.6 -Layout/SpaceInsideHashLiteralBraces: - Enabled: false -Layout/SpaceInsideBlockBraces: - Enabled: false -Layout/SpaceBeforeBlockBraces: - Enabled: false -Style/WordArray: - Enabled: false -Style/Documentation: - Enabled: false -Style/StringLiterals: - Enabled: false -Style/AsciiComments: - Enabled: false -Metrics/MethodLength: - Enabled: false -Metrics/LineLength: - Enabled: false -Metrics/BlockLength: - Enabled: false -Style/FrozenStringLiteralComment: - Enabled: false -Style/SymbolArray: - Enabled: false -Style/BlockDelimiters: - Enabled: false -Naming/VariableNumber: - Enabled: false -Rails/SkipsModelValidations: - Enabled: false -Style/EmptyMethod: - Enabled: false -Layout/LeadingCommentSpace: - Enabled: false -Metrics/AbcSize: - Enabled: false -Layout/ArgumentAlignment: - Enabled: false -Layout/HashAlignment: - Enabled: false -Style/IfUnlessModifier: - Enabled: false -Style/PercentLiteralDelimiters: - Enabled: false -Style/SoleNestedConditional: - Enabled: false -Rails/ActiveRecordCallbacksOrder: # new in 2.7 - Enabled: true -Rails/WhereNot: # new in 2.8 - Enabled: true -Rails/RedundantPresenceValidationOnBelongsTo: # new in 2.13 - Enabled: true -Style/GuardClause: - Enabled: false -Layout/EmptyLinesAroundAccessModifier: - Enabled: false +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/.ruby-version b/.ruby-version index 5ae69bd5f0..34cde5690e 100644 --- a/.ruby-version +++ b/.ruby-version @@ -1 +1 @@ -3.2.5 +3.2.6 diff --git a/Dockerfile b/Dockerfile index 7e5f178499..61792430f1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ # syntax = docker/dockerfile:1 # Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile -ARG RUBY_VERSION=3.2.5 +ARG RUBY_VERSION=3.2.6 FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base # Rails app lives here @@ -28,7 +28,7 @@ RUN apt-get update -qq && apt-get install --no-install-recommends -y curl gnupg apt-get install --no-install-recommends -y build-essential git libpq-dev libvips pkg-config nodejs yarn # Install application gems -COPY Gemfile Gemfile.lock ./ +COPY Gemfile Gemfile.lock package.json yarn.lock ./ RUN bundle install && \ rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ bundle exec bootsnap precompile --gemfile && \ @@ -41,7 +41,8 @@ COPY . . RUN bundle exec bootsnap precompile app/ lib/ # Precompiling assets for production without requiring secret RAILS_MASTER_KEY -# RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile +ARG NODE_OPTIONS=--openssl-legacy-provider +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile # Final stage for app image diff --git a/Gemfile b/Gemfile index 16e13c0d0b..d5a3981e40 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } -ruby "3.2.5" +ruby "3.2.6" # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" gem "rails", "~> 7.1.3", ">= 7.1.3.4" @@ -51,6 +51,9 @@ gem "image_processing", "~> 1.2" group :development, :test do # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem gem "debug", platforms: %i[ mri windows ] + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false end group :development do @@ -95,8 +98,8 @@ gem 'addressable' gem 'progress_bar' gem 'rails_autolink' gem 'kramdown' -gem 'solid_queue' -gem 'mission_control-jobs' +gem 'solid_queue', "~> 1.0" +gem 'mission_control-jobs', "~> 0.5.0" gem 'acts-as-taggable-on' gem 'resync' # , github: 'nabeta/resync', branch: 'add-datetime' gem 'pretender' @@ -109,7 +112,6 @@ gem 'rdf-turtle', require: 'rdf/turtle' gem 'rdf-vocab', require: 'rdf/vocab' gem 'oai' gem 'active_storage_validations' -gem 'sprockets', '~> 3.7' gem 'webpacker', '~> 5.0' gem 'faraday-multipart' diff --git a/Gemfile.lock b/Gemfile.lock index 6fa476e093..861ceac2a4 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,35 +1,35 @@ GEM remote: https://rubygems.org/ specs: - actioncable (7.1.3.4) - actionpack (= 7.1.3.4) - activesupport (= 7.1.3.4) + actioncable (7.1.5.1) + actionpack (= 7.1.5.1) + activesupport (= 7.1.5.1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) zeitwerk (~> 2.6) - actionmailbox (7.1.3.4) - actionpack (= 7.1.3.4) - activejob (= 7.1.3.4) - activerecord (= 7.1.3.4) - activestorage (= 7.1.3.4) - activesupport (= 7.1.3.4) + actionmailbox (7.1.5.1) + actionpack (= 7.1.5.1) + activejob (= 7.1.5.1) + activerecord (= 7.1.5.1) + activestorage (= 7.1.5.1) + activesupport (= 7.1.5.1) mail (>= 2.7.1) net-imap net-pop net-smtp - actionmailer (7.1.3.4) - actionpack (= 7.1.3.4) - actionview (= 7.1.3.4) - activejob (= 7.1.3.4) - activesupport (= 7.1.3.4) + actionmailer (7.1.5.1) + actionpack (= 7.1.5.1) + actionview (= 7.1.5.1) + activejob (= 7.1.5.1) + activesupport (= 7.1.5.1) mail (~> 2.5, >= 2.5.4) net-imap net-pop net-smtp rails-dom-testing (~> 2.2) - actionpack (7.1.3.4) - actionview (= 7.1.3.4) - activesupport (= 7.1.3.4) + actionpack (7.1.5.1) + actionview (= 7.1.5.1) + activesupport (= 7.1.5.1) nokogiri (>= 1.8.5) racc rack (>= 2.2.4) @@ -37,52 +37,57 @@ GEM rack-test (>= 0.6.3) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - actiontext (7.1.3.4) - actionpack (= 7.1.3.4) - activerecord (= 7.1.3.4) - activestorage (= 7.1.3.4) - activesupport (= 7.1.3.4) + actiontext (7.1.5.1) + actionpack (= 7.1.5.1) + activerecord (= 7.1.5.1) + activestorage (= 7.1.5.1) + activesupport (= 7.1.5.1) globalid (>= 0.6.0) nokogiri (>= 1.8.5) - actionview (7.1.3.4) - activesupport (= 7.1.3.4) + actionview (7.1.5.1) + activesupport (= 7.1.5.1) builder (~> 3.1) erubi (~> 1.11) rails-dom-testing (~> 2.2) rails-html-sanitizer (~> 1.6) - active_storage_validations (1.1.4) - activejob (>= 5.2.0) - activemodel (>= 5.2.0) - activestorage (>= 5.2.0) - activesupport (>= 5.2.0) - activejob (7.1.3.4) - activesupport (= 7.1.3.4) + active_storage_validations (2.0.1) + activejob (>= 6.1.4) + activemodel (>= 6.1.4) + activestorage (>= 6.1.4) + activesupport (>= 6.1.4) + marcel (>= 1.0.3) + activejob (7.1.5.1) + activesupport (= 7.1.5.1) globalid (>= 0.3.6) - activemodel (7.1.3.4) - activesupport (= 7.1.3.4) - activerecord (7.1.3.4) - activemodel (= 7.1.3.4) - activesupport (= 7.1.3.4) + activemodel (7.1.5.1) + activesupport (= 7.1.5.1) + activerecord (7.1.5.1) + activemodel (= 7.1.5.1) + activesupport (= 7.1.5.1) timeout (>= 0.4.0) - activestorage (7.1.3.4) - actionpack (= 7.1.3.4) - activejob (= 7.1.3.4) - activerecord (= 7.1.3.4) - activesupport (= 7.1.3.4) + activestorage (7.1.5.1) + actionpack (= 7.1.5.1) + activejob (= 7.1.5.1) + activerecord (= 7.1.5.1) + activesupport (= 7.1.5.1) marcel (~> 1.0) - activesupport (7.1.3.4) + activesupport (7.1.5.1) base64 + benchmark (>= 0.3) bigdecimal concurrent-ruby (~> 1.0, >= 1.0.2) connection_pool (>= 2.2.5) drb i18n (>= 1.6, < 2) + logger (>= 1.4.2) minitest (>= 5.1) mutex_m + securerandom (>= 0.3) tzinfo (~> 2.0) - acts-as-taggable-on (10.0.0) - activerecord (>= 6.1, < 7.2) - acts_as_list (1.2.2) + acts-as-taggable-on (12.0.0) + activerecord (>= 7.1, < 8.1) + zeitwerk (>= 2.4, < 3.0) + acts_as_list (1.2.4) activerecord (>= 6.1) activesupport (>= 6.1) addressable (2.8.7) @@ -90,16 +95,18 @@ GEM annotate (3.2.0) activerecord (>= 3.2, < 8.0) rake (>= 10.4, < 14.0) - awesome_nested_set (3.6.0) - activerecord (>= 4.0.0, < 7.2) + ast (2.4.2) + awesome_nested_set (3.8.0) + activerecord (>= 4.0.0, < 8.1) base64 (0.2.0) bcp47_spec (0.2.1) bcrypt (3.1.20) - bigdecimal (3.1.8) + benchmark (0.4.0) + bigdecimal (3.1.9) bindex (0.8.1) bootsnap (1.18.4) msgpack (~> 1.2) - browser (6.0.0) + browser (6.2.0) builder (3.3.0) capybara (3.40.0) addressable @@ -110,7 +117,7 @@ GEM rack-test (>= 0.6.3) regexp_parser (>= 1.5, < 3.0) xpath (~> 3.2) - caxlsx (4.1.0) + caxlsx (4.2.0) htmlentities (~> 4.3, >= 4.3.4) marcel (~> 1.0) nokogiri (~> 1.10, >= 1.10.4) @@ -120,20 +127,20 @@ GEM caxlsx (>= 3.0) climate_control (1.2.0) cocoon (1.2.15) - concurrent-ruby (1.3.4) - connection_pool (2.4.1) + concurrent-ruby (1.3.5) + connection_pool (2.5.0) crack (1.0.0) bigdecimal rexml crass (1.0.6) - csv (3.3.0) - database_consistency (1.7.23) + csv (3.3.2) + database_consistency (2.0.3) activerecord (>= 3.2) - date (3.3.4) + date (3.4.1) date_validator (0.12.0) activemodel (>= 3) activesupport (>= 3) - debug (1.9.2) + debug (1.10.0) irb (~> 1.10) reline (>= 0.3.8) devise (4.9.4) @@ -144,69 +151,73 @@ GEM warden (~> 1.2.3) diff-lcs (1.5.1) docile (1.4.1) - dotenv (3.1.2) - dotenv-rails (3.1.2) - dotenv (= 3.1.2) + dotenv (3.1.7) + dotenv-rails (3.1.7) + dotenv (= 3.1.7) railties (>= 6.1) drb (2.2.1) - ebnf (2.5.0) + ebnf (2.6.0) + base64 (~> 0.2) htmlentities (~> 4.3) rdf (~> 3.3) scanf (~> 1.0) sxp (~> 2.0) unicode-types (~> 1.8) - erubi (1.13.0) + erubi (1.13.1) et-orbi (1.2.11) tzinfo - factory_bot (6.4.6) - activesupport (>= 5.0.0) - factory_bot_rails (6.4.3) - factory_bot (~> 6.4) + factory_bot (6.5.1) + activesupport (>= 6.1.0) + factory_bot_rails (6.4.4) + factory_bot (~> 6.5) railties (>= 5.0.0) - faraday (2.10.1) - faraday-net_http (>= 2.0, < 3.2) + faraday (2.12.2) + faraday-net_http (>= 2.0, < 3.5) + json logger faraday-follow_redirects (0.3.0) faraday (>= 1, < 3) - faraday-multipart (1.0.4) - multipart-post (~> 2) - faraday-net_http (3.1.1) - net-http - ffi (1.17.0-x86_64-linux-gnu) + faraday-multipart (1.1.0) + multipart-post (~> 2.0) + faraday-net_http (3.4.0) + net-http (>= 0.5.0) + ffi (1.17.1-x86_64-linux-gnu) friendly_id (5.5.1) activerecord (>= 4.0.0) fugit (1.11.1) et-orbi (~> 1, >= 1.2.11) raabro (~> 1.4) - geocoder (1.8.3) + geocoder (1.8.5) base64 (>= 0.1.0) csv (>= 3.0.0) globalid (1.2.1) activesupport (>= 6.1) - globalize (6.3.0) - activemodel (>= 4.2, < 7.2) - activerecord (>= 4.2, < 7.2) + globalize (7.0.0) + activemodel (>= 7.0, < 8.1) + activerecord (>= 7.0, < 8.1) + activesupport (>= 7.0, < 8.1) request_store (~> 1.0) globalize-accessors (0.3.0) globalize (>= 5.0.0) - hashdiff (1.1.1) - highline (3.1.0) + hashdiff (1.1.2) + highline (3.1.2) reline htmlentities (4.3.4) - i18n (1.14.5) + i18n (1.14.7) concurrent-ruby (~> 1.0) image_processing (1.13.0) mini_magick (>= 4.9.5, < 5) ruby-vips (>= 2.0.17, < 3) - importmap-rails (2.0.1) + importmap-rails (2.1.0) actionpack (>= 6.0.0) activesupport (>= 6.0.0) railties (>= 6.0.0) - io-console (0.7.2) - irb (1.14.0) + io-console (0.8.0) + irb (1.15.1) + pp (>= 0.6.0) rdoc (>= 4.0.0) reline (>= 0.4.2) - jbuilder (2.12.0) + jbuilder (2.13.0) actionview (>= 5.0.0) activesupport (>= 5.0.0) jquery-rails (4.6.0) @@ -215,6 +226,7 @@ GEM thor (>= 0.14, < 2.0) jquery-ui-rails (4.2.1) railties (>= 3.2.16) + json (2.9.1) kaminari (1.2.2) activesupport (>= 4.1.0) kaminari-actionview (= 1.2.2) @@ -227,21 +239,22 @@ GEM activerecord kaminari-core (= 1.2.2) kaminari-core (1.2.2) - kramdown (2.4.0) - rexml + kramdown (2.5.1) + rexml (>= 3.3.9) kt-paperclip (7.2.2) activemodel (>= 4.2.0) activesupport (>= 4.2.0) marcel (~> 1.0.1) mime-types terrapin (>= 0.6.0, < 2.0) + language_server-protocol (3.17.0.4) library_stdnums (1.6.0) link_header (0.0.8) lisbn (0.3.2) nokogiri nori (~> 2.0) - logger (1.6.0) - loofah (2.22.0) + logger (1.6.5) + loofah (2.24.0) crass (~> 1.0.2) nokogiri (>= 1.12.0) mail (2.8.1) @@ -251,24 +264,29 @@ GEM net-smtp marcel (1.0.4) matrix (0.4.2) - mime-types (3.5.2) + mime-types (3.6.0) + logger mime-types-data (~> 3.2015) - mime-types-data (3.2024.0806) + mime-types-data (3.2025.0107) mini_magick (4.13.2) mini_mime (1.1.5) - minitest (5.25.1) - mission_control-jobs (0.3.1) - importmap-rails + minitest (5.25.4) + mission_control-jobs (0.5.0) + actioncable (>= 7.1) + actionpack (>= 7.1) + activejob (>= 7.1) + activerecord (>= 7.1) + importmap-rails (>= 1.2.1) irb (~> 1.13) - rails (>= 7.1) + railties (>= 7.1) stimulus-rails turbo-rails - msgpack (1.7.2) + msgpack (1.7.5) multipart-post (2.4.1) - mutex_m (0.2.0) - net-http (0.4.1) + mutex_m (0.3.0) + net-http (0.6.0) uri - net-imap (0.4.14) + net-imap (0.5.5) date net-protocol net-pop (0.1.2) @@ -277,8 +295,8 @@ GEM timeout net-smtp (0.5.0) net-protocol - nio4r (2.7.3) - nokogiri (1.16.7-x86_64-linux) + nio4r (2.7.4) + nokogiri (1.18.2-x86_64-linux-gnu) racc (~> 1.4) nori (2.7.1) bigdecimal @@ -289,48 +307,55 @@ GEM options (2.3.2) orm_adapter (0.5.0) parallel (1.26.3) - parallel_tests (4.7.1) + parallel_tests (4.9.0) parallel - pg (1.5.7) + parser (3.3.7.0) + ast (~> 2.4.1) + racc + pg (1.5.9) + pp (0.6.2) + prettyprint pr_geohash (1.0.0) pretender (0.5.0) actionpack (>= 6.1) + prettyprint (0.2.0) progress_bar (1.3.4) highline (>= 1.6) options (~> 2.3.0) - psych (5.1.2) + psych (5.2.3) + date stringio public_suffix (6.0.1) - puma (6.4.2) + puma (6.6.0) nio4r (~> 2.0) - pundit (2.3.2) + pundit (2.4.0) activesupport (>= 3.0.0) raabro (1.4.0) racc (1.8.1) - rack (2.2.9) + rack (3.1.9) rack-proxy (0.7.7) rack - rack-session (1.0.2) - rack (< 3) - rack-test (2.1.0) + rack-session (2.1.0) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) rack (>= 1.3) - rackup (1.0.0) - rack (< 3) - webrick - rails (7.1.3.4) - actioncable (= 7.1.3.4) - actionmailbox (= 7.1.3.4) - actionmailer (= 7.1.3.4) - actionpack (= 7.1.3.4) - actiontext (= 7.1.3.4) - actionview (= 7.1.3.4) - activejob (= 7.1.3.4) - activemodel (= 7.1.3.4) - activerecord (= 7.1.3.4) - activestorage (= 7.1.3.4) - activesupport (= 7.1.3.4) + rackup (2.2.1) + rack (>= 3) + rails (7.1.5.1) + actioncable (= 7.1.5.1) + actionmailbox (= 7.1.5.1) + actionmailer (= 7.1.5.1) + actionpack (= 7.1.5.1) + actiontext (= 7.1.5.1) + actionview (= 7.1.5.1) + activejob (= 7.1.5.1) + activemodel (= 7.1.5.1) + activerecord (= 7.1.5.1) + activestorage (= 7.1.5.1) + activesupport (= 7.1.5.1) bundler (>= 1.15.0) - railties (= 7.1.3.4) + railties (= 7.1.5.1) rails-controller-testing (1.0.5) actionpack (>= 5.0.1.rc1) actionview (>= 5.0.1.rc1) @@ -339,24 +364,25 @@ GEM activesupport (>= 5.0.0) minitest nokogiri (>= 1.6) - rails-html-sanitizer (1.6.0) + rails-html-sanitizer (1.6.2) loofah (~> 2.21) - nokogiri (~> 1.14) - rails-i18n (7.0.9) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + rails-i18n (7.0.10) i18n (>= 0.7, < 2) railties (>= 6.0.0, < 8) rails_autolink (1.1.8) actionview (> 3.1) activesupport (> 3.1) railties (> 3.1) - railties (7.1.3.4) - actionpack (= 7.1.3.4) - activesupport (= 7.1.3.4) + railties (7.1.5.1) + actionpack (= 7.1.5.1) + activesupport (= 7.1.5.1) irb rackup (>= 1.0.0) rake (>= 12.2) thor (~> 1.0, >= 1.2.2) zeitwerk (~> 2.6) + rainbow (3.1.1) rake (13.2.1) rdf (3.3.2) bcp47_spec (~> 0.2) @@ -367,16 +393,16 @@ GEM bigdecimal (~> 3.1, >= 3.1.5) ebnf (~> 2.5) rdf (~> 3.3) - rdf-vocab (3.3.1) + rdf-vocab (3.3.2) rdf (~> 3.3) - rdoc (6.7.0) + rdoc (6.11.0) psych (>= 4.0.0) - redis (5.2.0) + redis (5.3.0) redis-client (>= 0.22.0) - redis-client (0.22.2) + redis-client (0.23.2) connection_pool - regexp_parser (2.9.2) - reline (0.5.9) + regexp_parser (2.10.0) + reline (0.6.0) io-console (~> 0.5) request_store (1.7.0) rack (>= 1.4) @@ -388,36 +414,64 @@ GEM typesafe_enum (~> 0.1, >= 0.1.5) xml-mapping (~> 0.10) xml-mapping_extensions (~> 0.4, >= 0.4.8) - rexml (3.3.5) - strscan + rexml (3.4.0) rsolr (2.6.0) builder (>= 2.1.2) faraday (>= 0.9, < 3, != 2.0.0) - rspec-core (3.13.0) + rspec-core (3.13.2) rspec-support (~> 3.13.0) - rspec-expectations (3.13.1) + rspec-expectations (3.13.3) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-mocks (3.13.1) + rspec-mocks (3.13.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-rails (6.1.4) - actionpack (>= 6.1) - activesupport (>= 6.1) - railties (>= 6.1) + rspec-rails (7.1.0) + actionpack (>= 7.0) + activesupport (>= 7.0) + railties (>= 7.0) rspec-core (~> 3.13) rspec-expectations (~> 3.13) rspec-mocks (~> 3.13) rspec-support (~> 3.13) - rspec-support (3.13.1) + rspec-support (3.13.2) rspec_junit_formatter (0.6.0) rspec-core (>= 2, < 4, != 2.12.0) rss (0.3.1) rexml + rubocop (1.71.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.38.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.38.0) + parser (>= 3.3.1.0) + rubocop-minitest (0.36.0) + rubocop (>= 1.61, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-performance (1.23.1) + rubocop (>= 1.48.1, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails (2.29.1) + activesupport (>= 4.2.0) + rack (>= 1.1) + rubocop (>= 1.52.0, < 2.0) + rubocop-ast (>= 1.31.1, < 2.0) + rubocop-rails-omakase (1.0.0) + rubocop + rubocop-minitest + rubocop-performance + rubocop-rails + ruby-progressbar (1.13.0) ruby-vips (2.2.2) ffi (~> 1.12) logger - rubyzip (2.3.2) + rubyzip (2.4.1) sassc (2.4.0) ffi (~> 1.9) sassc-rails (2.1.2) @@ -427,31 +481,32 @@ GEM sprockets-rails tilt scanf (1.0.0) - selenium-webdriver (4.23.0) + securerandom (0.4.1) + selenium-webdriver (4.28.0) base64 (~> 0.2) logger (~> 1.4) rexml (~> 3.2, >= 3.2.5) rubyzip (>= 1.2.2, < 3.0) websocket (~> 1.0) - semantic_range (3.0.0) + semantic_range (3.1.0) simplecov (0.22.0) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) - simplecov-html (0.12.3) + simplecov-html (0.13.1) simplecov_json_formatter (0.1.4) sitemap_generator (6.3.0) builder (~> 3.0) - solid_queue (0.5.0) + solid_queue (1.1.3) activejob (>= 7.1) activerecord (>= 7.1) concurrent-ruby (>= 1.3.1) fugit (~> 1.11.0) railties (>= 7.1) - sprockets (3.7.3) - base64 + thor (~> 1.3.1) + sprockets (4.2.1) concurrent-ruby (~> 1.0) - rack (> 1, < 3) + rack (>= 2.2.4, < 4) sprockets-rails (3.5.2) actionpack (>= 6.1) activesupport (>= 6.1) @@ -459,10 +514,9 @@ GEM statesman (12.1.0) stimulus-rails (1.3.4) railties (>= 6.0.0) - stringio (3.1.1) - strip_attributes (1.13.0) - activemodel (>= 3.0, < 8.0) - strscan (3.1.0) + stringio (3.1.2) + strip_attributes (1.14.1) + activemodel (>= 3.0, < 9.0) sunspot (2.7.1) bigdecimal pr_geohash (~> 1.0) @@ -475,19 +529,22 @@ GEM rdf (~> 3.3) terrapin (1.0.1) climate_control - thor (1.3.1) - tilt (2.4.0) - timeout (0.4.1) - turbo-rails (2.0.6) + thor (1.3.2) + tilt (2.6.0) + timeout (0.4.3) + turbo-rails (2.0.11) actionpack (>= 6.0.0) - activejob (>= 6.0.0) railties (>= 6.0.0) typesafe_enum (0.3.1) tzinfo (2.0.6) concurrent-ruby (~> 1.0) - unicode-types (1.9.0) - uri (0.13.0) - vcr (6.2.0) + unicode-display_width (3.1.4) + unicode-emoji (~> 4.0, >= 4.0.4) + unicode-emoji (4.0.4) + unicode-types (1.10.0) + uri (1.0.2) + vcr (6.3.1) + base64 warden (1.2.9) rack (>= 2.0.9) web-console (4.2.1) @@ -495,7 +552,7 @@ GEM activemodel (>= 6.0.0) bindex (>= 0.4.0) railties (>= 6.0.0) - webmock (3.23.1) + webmock (3.24.0) addressable (>= 2.8.0) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) @@ -504,9 +561,9 @@ GEM rack-proxy (>= 0.6.1) railties (>= 5.2) semantic_range (>= 2.3.0) - webrick (1.8.1) websocket (1.2.11) - websocket-driver (0.7.6) + websocket-driver (0.7.7) + base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) xml-mapping (0.10.1) @@ -516,7 +573,7 @@ GEM xml-mapping (~> 0.10) xpath (3.2.0) nokogiri (~> 1.8) - zeitwerk (2.6.17) + zeitwerk (2.7.1) PLATFORMS x86_64-linux @@ -554,7 +611,7 @@ DEPENDENCIES kt-paperclip library_stdnums lisbn - mission_control-jobs + mission_control-jobs (~> 0.5.0) oai parallel_tests pg (~> 1.1) @@ -573,12 +630,12 @@ DEPENDENCIES rspec-rails rspec_junit_formatter rss + rubocop-rails-omakase sassc-rails selenium-webdriver simplecov sitemap_generator - solid_queue - sprockets (~> 3.7) + solid_queue (~> 1.0) sprockets-rails statesman (~> 12.1) strip_attributes @@ -590,7 +647,7 @@ DEPENDENCIES webpacker (~> 5.0) RUBY VERSION - ruby 3.2.5p208 + ruby 3.2.6p234 BUNDLED WITH 2.4.19 diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js index b16e53d6d5..8dde2ae18e 100644 --- a/app/assets/config/manifest.js +++ b/app/assets/config/manifest.js @@ -1,3 +1,7 @@ //= link_tree ../images //= link_directory ../javascripts .js //= link_directory ../stylesheets .css +//= link application.css +//= link application.js +//= link mobile.css +//= link mobile.js diff --git a/app/controllers/active_storage/blobs/proxy_controller.rb b/app/controllers/active_storage/blobs/proxy_controller.rb index 3a0dff9271..fd4558318f 100644 --- a/app/controllers/active_storage/blobs/proxy_controller.rb +++ b/app/controllers/active_storage/blobs/proxy_controller.rb @@ -1,5 +1,6 @@ class ActiveStorage::Blobs::ProxyController < ActiveStorage::BaseController include ActiveStorage::SetBlob + include ActiveStorage::Streaming include Pundit::Authorization def show diff --git a/app/controllers/checkouts_controller.rb b/app/controllers/checkouts_controller.rb index ff69557a6c..124815e242 100644 --- a/app/controllers/checkouts_controller.rb +++ b/app/controllers/checkouts_controller.rb @@ -178,10 +178,4 @@ def check_policy def checkout_params params.fetch(:checkout, {}).permit(:due_date) end - - def filtered_params - params.permit([:user_id, :days_overdue, :reserved]) - end - - helper_method :filtered_params end diff --git a/app/controllers/concerns/enju_library/controller.rb b/app/controllers/concerns/enju_library/controller.rb index 216fb8cfec..26a5d0f404 100644 --- a/app/controllers/concerns/enju_library/controller.rb +++ b/app/controllers/concerns/enju_library/controller.rb @@ -8,7 +8,6 @@ module Controller rescue_from Pundit::NotAuthorizedError, with: :render_403 # rescue_from ActiveRecord::RecordNotFound, with: :render_404 # rescue_from ActionView::MissingTemplate, with: :render_404_invalid_format - helper_method :filtered_params end private @@ -246,10 +245,6 @@ def get_subscription end end - def filtered_params - params.permit([:q, :query, :view, :format, :order, :sort_by, :page, :per_page]) - end - class InvalidLocaleError < StandardError end end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index 8557618415..c73e662f7d 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -160,10 +160,4 @@ def event_params def prepare_options @event_categories = EventCategory.all end - - def filtered_params - params.permit([:format, :library_id, :mode, :query, :page, :per_page]) - end - - helper_method :filtered_params end diff --git a/app/controllers/library_groups_controller.rb b/app/controllers/library_groups_controller.rb index 601055eb4f..27a9a0ed09 100644 --- a/app/controllers/library_groups_controller.rb +++ b/app/controllers/library_groups_controller.rb @@ -65,7 +65,7 @@ def library_group_params :name, :display_name, :short_name, :my_networks, :login_banner, :note, :country_id, :admin_networks, :url, :max_number_of_results, :footer_banner, :email, - :book_jacket_source, :screenshot_generator, :erms_url, + :book_jacket_source, :screenshot_generator, :header_logo, :delete_header_logo, :allow_bookmark_external_url, # EnjuBookmark { diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index fada058b27..a8735d41c2 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -166,10 +166,4 @@ def get_parent(id) end end end - - def filtered_params - params.permit([:view, :format, :page, :mode, :sort_by, :per_page]) - end - - helper_method :filtered_params end diff --git a/app/controllers/picture_files_controller.rb b/app/controllers/picture_files_controller.rb index 8ec86bd364..3910465634 100644 --- a/app/controllers/picture_files_controller.rb +++ b/app/controllers/picture_files_controller.rb @@ -27,6 +27,12 @@ def show end end + def download + picture_file = PictureFile.find(params[:picture_file_id]) + authorize picture_file, policy_class: PictureFilePolicy + redirect_to rails_storage_proxy_url(picture_file.attachment) + end + # GET /picture_files/new def new unless @attachable diff --git a/app/controllers/reserves_controller.rb b/app/controllers/reserves_controller.rb index 2beb60cd4c..8f63edc7e6 100644 --- a/app/controllers/reserves_controller.rb +++ b/app/controllers/reserves_controller.rb @@ -298,10 +298,4 @@ def reserve_update_params def prepare_options @libraries = Library.real.order(:position) end - - def filtered_params - params.permit([:user_id, :reserved_from, :reserved_until, :query, :sort_by, :state]) - end - - helper_method :filtered_params end diff --git a/app/helpers/checkouts_helper.rb b/app/helpers/checkouts_helper.rb new file mode 100644 index 0000000000..15894b3fda --- /dev/null +++ b/app/helpers/checkouts_helper.rb @@ -0,0 +1,5 @@ +module CheckoutsHelper + def filtered_params + params.permit([:user_id, :days_overdue, :reserved]) + end +end diff --git a/app/helpers/enju_biblio/application_helper.rb b/app/helpers/enju_biblio/application_helper.rb index 1c532574c0..7648416e20 100644 --- a/app/helpers/enju_biblio/application_helper.rb +++ b/app/helpers/enju_biblio/application_helper.rb @@ -47,30 +47,23 @@ def agents_list(agents = [], options = {}) if options[:nolink] agents_list = agents.map{|agent| agent.full_name} else - agents_list = agents.map{|agent| link_to(agent.full_name, manifestations_path(query: "\"#{agent.full_name}\""), options)} + agents_list = agents.map{|agent| + link_to(agent.full_name, manifestations_path(query: "\"#{agent.full_name}\""), options) + ' ' + (link_to("[A]", agent_path(agent)) if agent.ndla_record) + } end agents_list.join(" ").html_safe end - def identifier_link(identifier) - case identifier.identifier_type.name - when 'doi' - link_to identifier.body, "https://doi.org/#{identifier.body}" - when 'iss_itemno' - if identifier.body =~ /\AR[0-9A-Za-z]+?-I[0-9A-Za-z]+?-00\z/ - link_to identifier.body, "https://iss.ndl.go.jp/books/#{identifier.body}" - else - link_to identifier.body, "https://ndlsearch.ndl.go.jp/books/#{identifier.body}" - end - when 'lccn' - link_to identifier.body, "https://lccn.loc.gov/#{identifier.body}" - when 'ncid' - link_to identifier.body, "https://ci.nii.ac.jp/ncid/#{identifier.body}" - when 'isbn' - Lisbn.new(identifier.body).isbn_with_dash + def ndl_bib_id_record_link(ndl_bib_id_record) + if ndl_bib_id_record.body =~ /\AR[0-9A-Za-z]+?-I[0-9A-Za-z]+?-00\z/ + link_to ndl_bib_id_record.body, "https://iss.ndl.go.jp/books/#{ndl_bib_id_record.body}" else - identifier.body + link_to ndl_bib_id_record.body, "https://ndlsearch.ndl.go.jp/books/#{ndl_bib_id_record.body}" end end + + def identifier_link(identifier) + identifier.body + end end end diff --git a/app/helpers/enju_manifestation_viewer/book_jacket_helper.rb b/app/helpers/enju_manifestation_viewer/book_jacket_helper.rb index f431342318..41df9904cc 100644 --- a/app/helpers/enju_manifestation_viewer/book_jacket_helper.rb +++ b/app/helpers/enju_manifestation_viewer/book_jacket_helper.rb @@ -44,11 +44,11 @@ def book_jacket_tag(manifestation, generator = LibraryGroup.site_config.book_jac case generator when "amazon" - return nil unless LibraryGroup.site_config.settings[:amazon_hostname] + return nil unless LibraryGroup.site_config.amazon_hostname book_jacket = manifestation.amazon_book_jacket if book_jacket - link_to image_tag(book_jacket[:url], width: book_jacket[:width], height: book_jacket[:height], alt: manifestation.original_title, class: 'book_jacket', itemprop: 'image'), "https://#{LibraryGroup.site_config.settings[:amazon_hostname]}/dp/#{book_jacket[:asin]}" + link_to image_tag(book_jacket[:url], width: book_jacket[:width], height: book_jacket[:height], alt: manifestation.original_title, class: 'book_jacket', itemprop: 'image'), "https://#{LibraryGroup.site_config.amazon_hostname}/dp/#{book_jacket[:asin]}" end when "google" render partial: 'manifestations/google_book_thumbnail', locals: {manifestation: manifestation} @@ -59,7 +59,7 @@ def book_jacket_tag(manifestation, generator = LibraryGroup.site_config.book_jac end end - def amazon_link(asin, hostname = LibraryGroup.site_config.settings[:amazon_hostname]) + def amazon_link(asin, hostname = LibraryGroup.site_config.amazon_hostname) return nil if asin.blank? "https://#{hostname}/dp/#{asin}" diff --git a/app/helpers/events_helper.rb b/app/helpers/events_helper.rb new file mode 100644 index 0000000000..c44cdcca50 --- /dev/null +++ b/app/helpers/events_helper.rb @@ -0,0 +1,5 @@ +module EventsHelper + def filtered_params + params.permit([:format, :library_id, :mode, :query, :page, :per_page]) + end +end diff --git a/app/helpers/libraries_helper.rb b/app/helpers/libraries_helper.rb new file mode 100644 index 0000000000..fdee7aab74 --- /dev/null +++ b/app/helpers/libraries_helper.rb @@ -0,0 +1,5 @@ +module LibrariesHelper + def filtered_params + params.permit([:q, :query, :view, :format, :order, :sort_by, :page, :per_page]) + end +end diff --git a/app/helpers/messages_helper.rb b/app/helpers/messages_helper.rb index f1bca9f6ca..2e77428b0d 100644 --- a/app/helpers/messages_helper.rb +++ b/app/helpers/messages_helper.rb @@ -1,2 +1,5 @@ module MessagesHelper + def filtered_params + params.permit([:view, :format, :page, :mode, :sort_by, :per_page]) + end end diff --git a/app/helpers/reserves_helper.rb b/app/helpers/reserves_helper.rb index 11e63253b8..36aed032d0 100644 --- a/app/helpers/reserves_helper.rb +++ b/app/helpers/reserves_helper.rb @@ -18,4 +18,8 @@ def i18n_state(state) t('reserve.completed') end end + + def filtered_params + params.permit([:user_id, :reserved_from, :reserved_until, :query, :sort_by, :state]) + end end diff --git a/app/models/accept.rb b/app/models/accept.rb index 0c1430fea1..17940d8103 100644 --- a/app/models/accept.rb +++ b/app/models/accept.rb @@ -1,9 +1,9 @@ class Accept < ApplicationRecord include EnjuCirculation::EnjuAccept - default_scope { order('accepts.id DESC') } + default_scope { order("accepts.id DESC") } belongs_to :basket belongs_to :item, touch: true - belongs_to :librarian, class_name: 'User' + belongs_to :librarian, class_name: "User" validates :item_id, uniqueness: true # , message: I18n.t('accept.already_accepted') diff --git a/app/models/agent.rb b/app/models/agent.rb index d30da56682..fc028dc080 100644 --- a/app/models/agent.rb +++ b/app/models/agent.rb @@ -1,11 +1,11 @@ class Agent < ApplicationRecord include EnjuNdl::EnjuAgent - scope :readable_by, lambda{ |user| + scope :readable_by, lambda { |user| if user - where('required_role_id <= ?', user.try(:user_has_role).try(:role_id)) + where("required_role_id <= ?", user.try(:user_has_role).try(:role_id)) else - where('required_role_id <= 1') + where("required_role_id <= 1") end } has_many :creates, dependent: :destroy @@ -14,8 +14,8 @@ class Agent < ApplicationRecord has_many :expressions, through: :realizes has_many :produces, dependent: :destroy has_many :manifestations, through: :produces - has_many :children, foreign_key: 'parent_id', class_name: 'AgentRelationship', dependent: :destroy, inverse_of: :parent - has_many :parents, foreign_key: 'child_id', class_name: 'AgentRelationship', dependent: :destroy, inverse_of: :child + has_many :children, foreign_key: "parent_id", class_name: "AgentRelationship", dependent: :destroy, inverse_of: :parent + has_many :parents, foreign_key: "child_id", class_name: "AgentRelationship", dependent: :destroy, inverse_of: :child has_many :derived_agents, through: :children, source: :child has_many :original_agents, through: :parents, source: :parent has_many :picture_files, as: :picture_attachable, dependent: :destroy @@ -26,7 +26,7 @@ class Agent < ApplicationRecord has_many :agent_merges, dependent: :destroy has_many :agent_merge_lists, through: :agent_merges belongs_to :agent_type - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" belongs_to :language belongs_to :country has_one :agent_import_result @@ -40,17 +40,17 @@ class Agent < ApplicationRecord before_validation :set_role_and_name, on: :create before_save :set_date_of_birth, :set_date_of_death after_save do |agent| - agent.works.map{|work| work.touch && work.index} - agent.expressions.map{|expression| expression.touch && expression.index} - agent.manifestations.map{|manifestation| manifestation.touch && manifestation.index} - agent.items.map{|item| item.touch && item.index} + agent.works.map { |work| work.touch && work.index } + agent.expressions.map { |expression| expression.touch && expression.index } + agent.manifestations.map { |manifestation| manifestation.touch && manifestation.index } + agent.items.map { |item| item.touch && item.index } Sunspot.commit end after_destroy do |agent| - agent.works.map{|work| work.touch && work.index} - agent.expressions.map{|expression| expression.touch && expression.index} - agent.manifestations.map{|manifestation| manifestation.touch && manifestation.index} - agent.items.map{|item| item.touch && item.index} + agent.works.map { |work| work.touch && work.index } + agent.expressions.map { |expression| expression.touch && expression.index } + agent.manifestations.map { |manifestation| manifestation.touch && manifestation.index } + agent.items.map { |item| item.touch && item.index } Sunspot.commit end @@ -71,27 +71,30 @@ class Agent < ApplicationRecord integer :original_agent_ids, multiple: true integer :required_role_id integer :agent_type_id + string :agent_id do + id + end end paginates_per 10 def set_role_and_name - self.required_role = Role.find_by(name: 'Librarian') if required_role_id.nil? + self.required_role = Role.find_by(name: "Librarian") if required_role_id.nil? set_full_name end def set_full_name if full_name.blank? if LibraryGroup.site_config.family_name_first - self.full_name = [last_name, middle_name, first_name].compact.join(" ").to_s.strip + self.full_name = [ last_name, middle_name, first_name ].compact.join(" ").to_s.strip else - self.full_name = [first_name, last_name, middle_name].compact.join(" ").to_s.strip + self.full_name = [ first_name, last_name, middle_name ].compact.join(" ").to_s.strip end end if full_name_transcription.blank? - self.full_name_transcription = [last_name_transcription, middle_name_transcription, first_name_transcription].join(" ").to_s.strip + self.full_name_transcription = [ last_name_transcription, middle_name_transcription, first_name_transcription ].join(" ").to_s.strip end - [full_name, full_name_transcription] + [ full_name, full_name_transcription ] end def set_date_of_birth @@ -142,7 +145,7 @@ def check_birth_date end end - #def full_name_generate + # def full_name_generate # # TODO: 日本人以外は? # name = [] # name << self.last_name.to_s.strip @@ -150,7 +153,7 @@ def check_birth_date # name << self.first_name.to_s.strip # name << self.corporate_name.to_s.strip # name.join(" ").strip - #end + # end def full_name_without_space full_name.gsub(/[\s,]/, "") @@ -177,11 +180,11 @@ def name name << full_name_transcription.to_s.strip name << full_name_alternative.to_s.strip name << full_name_without_space - #name << full_name_transcription_without_space - #name << full_name_alternative_without_space - #name << full_name.wakati rescue nil - #name << full_name_transcription.wakati rescue nil - #name << full_name_alternative.wakati rescue nil + # name << full_name_transcription_without_space + # name << full_name_alternative_without_space + # name << full_name.wakati rescue nil + # name << full_name_transcription.wakati rescue nil + # name << full_name_alternative.wakati rescue nil name end @@ -222,7 +225,7 @@ def owned(item) def self.import_agents(agent_lists) agents = [] agent_lists.each do |agent_list| - name_and_role = agent_list[:full_name].split('||') + name_and_role = agent_list[:full_name].split("||") if agent_list[:ndla_identifier].present? agent = NdlaRecord.find_by(body: agent_list[:ndla_identifier])&.agent elsif agent_list[:agent_identifier].present? @@ -242,7 +245,7 @@ def self.import_agents(agent_lists) place: agent_list[:place], language_id: 1 ) - agent.required_role = Role.find_by(name: 'Guest') + agent.required_role = Role.find_by(name: "Guest") agent.save if agent_list[:ndla_identifier].present? @@ -265,20 +268,20 @@ def self.new_agents(agents_params) agents = [] Agent.transaction do agents_params.each do |k, v| - next if v['_destroy'] == '1' + next if v["_destroy"] == "1" agent = nil - if v['agent_id'].present? - agent = Agent.find(v['agent_id']) - elsif v['id'].present? - agent = Agent.find(v['id']) + if v["agent_id"].present? + agent = Agent.find(v["agent_id"]) + elsif v["id"].present? + agent = Agent.find(v["id"]) end - if !agent or agent.full_name != v['full_name'] - v.delete('id') - v.delete('agent_id') - v.delete('_destroy') + if !agent or agent.full_name != v["full_name"] + v.delete("id") + v.delete("agent_id") + v.delete("_destroy") agent = Agent.create(v) end diff --git a/app/models/agent_import_file.rb b/app/models/agent_import_file.rb index 2734cd8046..bef37b18e0 100644 --- a/app/models/agent_import_file.rb +++ b/app/models/agent_import_file.rb @@ -4,9 +4,9 @@ class AgentImportFile < ApplicationRecord initial_state: AgentImportFileStateMachine.initial_state ] include ImportFile - default_scope { order('agent_import_files.id DESC') } + default_scope { order("agent_import_files.id DESC") } scope :not_imported, -> { in_state(:pending) } - scope :stucked, -> { in_state(:pending).where('agent_import_files.created_at < ?', 1.hour.ago) } + scope :stucked, -> { in_state(:pending).where("agent_import_files.created_at < ?", 1.hour.ago) } has_one_attached :attachment belongs_to :user @@ -25,11 +25,11 @@ def state_machine def import_start case edit_mode - when 'create' + when "create" import - when 'update' + when "update" modify - when 'destroy' + when "destroy" remove else import @@ -42,17 +42,17 @@ def import rows = open_import_file field = rows.first row_num = 1 - if [field['first_name'], field['last_name'], field['full_name']].reject{|field| field.to_s.strip == ""}.empty? + if [ field["first_name"], field["last_name"], field["full_name"] ].reject { |field| field.to_s.strip == "" }.empty? raise "You should specify first_name, last_name or full_name in the first line" end - #rows.shift + # rows.shift AgentImportResult.create!(agent_import_file_id: id, body: rows.headers.join("\t")) rows.each do |row| row_num += 1 import_result = AgentImportResult.create!(agent_import_file_id: id, body: row.fields.join("\t")) - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? agent = Agent.new agent = set_agent_value(agent, row) @@ -94,21 +94,21 @@ def modify rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? - agent = Agent.find_by(id: row['id']) + agent = Agent.find_by(id: row["id"]) next unless agent - agent.full_name = row['full_name'] if row['full_name'].to_s.strip.present? - agent.full_name_transcription = row['full_name_transcription'] if row['full_name_transcription'].to_s.strip.present? - agent.first_name = row['first_name'] if row['first_name'].to_s.strip.present? - agent.first_name_transcription = row['first_name_transcription'] if row['first_name_transcription'].to_s.strip.present? - agent.middle_name = row['middle_name'] if row['middle_name'].to_s.strip.present? - agent.middle_name_transcription = row['middle_name_transcription'] if row['middle_name_transcription'].to_s.strip.present? - agent.last_name = row['last_name'] if row['last_name'].to_s.strip.present? - agent.last_name_transcription = row['last_name_transcription'] if row['last_name_transcription'].to_s.strip.present? - agent.address_1 = row['address_1'] if row['address_1'].to_s.strip.present? - agent.address_2 = row['address_2'] if row['address_2'].to_s.strip.present? + agent.full_name = row["full_name"] if row["full_name"].to_s.strip.present? + agent.full_name_transcription = row["full_name_transcription"] if row["full_name_transcription"].to_s.strip.present? + agent.first_name = row["first_name"] if row["first_name"].to_s.strip.present? + agent.first_name_transcription = row["first_name_transcription"] if row["first_name_transcription"].to_s.strip.present? + agent.middle_name = row["middle_name"] if row["middle_name"].to_s.strip.present? + agent.middle_name_transcription = row["middle_name_transcription"] if row["middle_name_transcription"].to_s.strip.present? + agent.last_name = row["last_name"] if row["last_name"].to_s.strip.present? + agent.last_name_transcription = row["last_name_transcription"] if row["last_name_transcription"].to_s.strip.present? + agent.address_1 = row["address_1"] if row["address_1"].to_s.strip.present? + agent.address_2 = row["address_2"] if row["address_2"].to_s.strip.present? agent.save! end transition_to!(:completed) @@ -130,9 +130,9 @@ def remove rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? - agent = Agent.find_by(id: row['id'].to_s.strip) + agent = Agent.find_by(id: row["id"].to_s.strip) next unless agent agent.picture_files.destroy_all @@ -166,37 +166,37 @@ def open_import_file end def set_agent_value(agent, row) - agent.first_name = row['first_name'] if row['first_name'] - agent.middle_name = row['middle_name'] if row['middle_name'] - agent.last_name = row['last_name'] if row['last_name'] - agent.first_name_transcription = row['first_name_transcription'] if row['first_name_transcription'] - agent.middle_name_transcription = row['middle_name_transcription'] if row['middle_name_transcription'] - agent.last_name_transcription = row['last_name_transcription'] if row['last_name_transcription'] - - agent.full_name = row['full_name'] if row['full_name'] - agent.full_name_transcription = row['full_name_transcription'] if row['full_name_transcription'] - - agent.address_1 = row['address_1'] if row['address_1'] - agent.address_2 = row['address_2'] if row['address_2'] - agent.zip_code_1 = row['zip_code_1'] if row['zip_code_1'] - agent.zip_code_2 = row['zip_code_2'] if row['zip_code_2'] - agent.telephone_number_1 = row['telephone_number_1'] if row['telephone_number_1'] - agent.telephone_number_2 = row['telephone_number_2'] if row['telephone_number_2'] - agent.fax_number_1 = row['fax_number_1'] if row['fax_number_1'] - agent.fax_number_2 = row['fax_number_2'] if row['fax_number_2'] - agent.note = row['note'] if row['note'] - agent.birth_date = row['birth_date'] if row['birth_date'] - agent.death_date = row['death_date'] if row['death_date'] + agent.first_name = row["first_name"] if row["first_name"] + agent.middle_name = row["middle_name"] if row["middle_name"] + agent.last_name = row["last_name"] if row["last_name"] + agent.first_name_transcription = row["first_name_transcription"] if row["first_name_transcription"] + agent.middle_name_transcription = row["middle_name_transcription"] if row["middle_name_transcription"] + agent.last_name_transcription = row["last_name_transcription"] if row["last_name_transcription"] + + agent.full_name = row["full_name"] if row["full_name"] + agent.full_name_transcription = row["full_name_transcription"] if row["full_name_transcription"] + + agent.address_1 = row["address_1"] if row["address_1"] + agent.address_2 = row["address_2"] if row["address_2"] + agent.zip_code_1 = row["zip_code_1"] if row["zip_code_1"] + agent.zip_code_2 = row["zip_code_2"] if row["zip_code_2"] + agent.telephone_number_1 = row["telephone_number_1"] if row["telephone_number_1"] + agent.telephone_number_2 = row["telephone_number_2"] if row["telephone_number_2"] + agent.fax_number_1 = row["fax_number_1"] if row["fax_number_1"] + agent.fax_number_2 = row["fax_number_2"] if row["fax_number_2"] + agent.note = row["note"] if row["note"] + agent.birth_date = row["birth_date"] if row["birth_date"] + agent.death_date = row["death_date"] if row["death_date"] # if row['username'].to_s.strip.blank? - agent.email = row['email'].to_s.strip - agent.required_role = Role.find_by(name: row['required_role'].to_s.strip.camelize) || Role.find_by(name: 'Guest') + agent.email = row["email"].to_s.strip + agent.required_role = Role.find_by(name: row["required_role"].to_s.strip.camelize) || Role.find_by(name: "Guest") # else # agent.required_role = Role.where(name: row['required_role'].to_s.strip.camelize).first || Role.where('Librarian').first # end - language = Language.find_by(name: row['language'].to_s.strip.camelize) || Language.find_by(iso_639_2: row['language'].to_s.strip.downcase) || Language.find_by(iso_639_1: row['language'].to_s.strip.downcase) + language = Language.find_by(name: row["language"].to_s.strip.camelize) || Language.find_by(iso_639_2: row["language"].to_s.strip.downcase) || Language.find_by(iso_639_1: row["language"].to_s.strip.downcase) agent.language = language if language - country = Country.find_by(name: row['country'].to_s.strip) + country = Country.find_by(name: row["country"].to_s.strip) agent.country = country if country agent end diff --git a/app/models/agent_import_file_state_machine.rb b/app/models/agent_import_file_state_machine.rb index 11326be4e8..1c829e8fbc 100644 --- a/app/models/agent_import_file_state_machine.rb +++ b/app/models/agent_import_file_state_machine.rb @@ -6,8 +6,8 @@ class AgentImportFileStateMachine state :completed state :failed - transition from: :pending, to: [:started, :failed] - transition from: :started, to: [:completed, :failed] + transition from: :pending, to: [ :started, :failed ] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |agent_import_file| agent_import_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/agent_import_file_transition.rb b/app/models/agent_import_file_transition.rb index 6e1446a606..8fbed44c2a 100644 --- a/app/models/agent_import_file_transition.rb +++ b/app/models/agent_import_file_transition.rb @@ -1,7 +1,4 @@ class AgentImportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :agent_import_file, inverse_of: :agent_import_file_transitions end @@ -11,7 +8,7 @@ class AgentImportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # agent_import_file_id :bigint # created_at :datetime not null diff --git a/app/models/agent_import_result.rb b/app/models/agent_import_result.rb index a0389866d2..a40ad95a1b 100644 --- a/app/models/agent_import_result.rb +++ b/app/models/agent_import_result.rb @@ -1,6 +1,6 @@ class AgentImportResult < ApplicationRecord - default_scope { order('agent_import_results.id') } - scope :file_id, proc{|file_id| where(agent_import_file_id: file_id)} + default_scope { order("agent_import_results.id") } + scope :file_id, proc { |file_id| where(agent_import_file_id: file_id) } scope :failed, -> { where(agent_id: nil) } belongs_to :agent_import_file diff --git a/app/models/agent_relationship.rb b/app/models/agent_relationship.rb index f2362f7531..753281ee0e 100644 --- a/app/models/agent_relationship.rb +++ b/app/models/agent_relationship.rb @@ -1,6 +1,6 @@ class AgentRelationship < ApplicationRecord - belongs_to :parent, class_name: 'Agent' - belongs_to :child, class_name: 'Agent' + belongs_to :parent, class_name: "Agent" + belongs_to :child, class_name: "Agent" belongs_to :agent_relationship_type, optional: true validate :check_parent acts_as_list scope: :parent_id diff --git a/app/models/agent_relationship_type.rb b/app/models/agent_relationship_type.rb index 44ba72a3da..0e5a1fb566 100644 --- a/app/models/agent_relationship_type.rb +++ b/app/models/agent_relationship_type.rb @@ -1,6 +1,6 @@ class AgentRelationshipType < ApplicationRecord include MasterModel - default_scope { order('agent_relationship_types.position') } + default_scope { order("agent_relationship_types.position") } has_many :agent_relationships, dependent: :destroy end diff --git a/app/models/basket.rb b/app/models/basket.rb index 547d48056d..f22b986c83 100644 --- a/app/models/basket.rb +++ b/app/models/basket.rb @@ -1,7 +1,7 @@ class Basket < ApplicationRecord include EnjuCirculation::EnjuBasket - default_scope { order('baskets.id DESC') } - scope :will_expire, lambda {|date| where('created_at < ?', date)} + default_scope { order("baskets.id DESC") } + scope :will_expire, lambda { |date| where("created_at < ?", date) } belongs_to :user, optional: true has_many :accepts, dependent: :destroy has_many :withdraws, dependent: :destroy @@ -14,9 +14,9 @@ class Basket < ApplicationRecord def check_suspended if user - errors.add(:base, I18n.t('basket.this_account_is_suspended')) if user.locked_at + errors.add(:base, I18n.t("basket.this_account_is_suspended")) if user.locked_at else - errors.add(:base, I18n.t('user.not_found')) + errors.add(:base, I18n.t("user.not_found")) end end diff --git a/app/models/bookmark.rb b/app/models/bookmark.rb index 7109c05fab..31b54d0dbe 100644 --- a/app/models/bookmark.rb +++ b/app/models/bookmark.rb @@ -1,7 +1,7 @@ class Bookmark < ApplicationRecord - scope :bookmarked, lambda {|start_date, end_date| where('created_at >= ? AND created_at < ?', start_date, end_date)} - scope :user_bookmarks, lambda {|user| where(user_id: user.id)} - scope :shared, -> {where(shared: true)} + scope :bookmarked, lambda { |start_date, end_date| where("created_at >= ? AND created_at < ?", start_date, end_date) } + scope :user_bookmarks, lambda { |user| where(user_id: user.id) } + scope :shared, -> { where(shared: true) } belongs_to :manifestation, touch: true, optional: true belongs_to :user @@ -9,7 +9,7 @@ class Bookmark < ApplicationRecord validates :url, presence: { on: :create } validates :manifestation_id, presence: { on: :update } validates :manifestation_id, uniqueness: { scope: :user_id } - validates :url, url: true, presence: true, length: {maximum: 255} + validates :url, url: true, presence: true, length: { maximum: 255 } validate :bookmarkable_url? validate :already_bookmarked?, if: :url_changed? before_save :create_manifestation, if: :url_changed? @@ -37,7 +37,7 @@ class Bookmark < ApplicationRecord def replace_space_in_tags # タグに含まれている全角スペースを除去する - self.tag_list = tag_list.map{|tag| tag.gsub(' ', ' ').gsub(' ', ', ')} + self.tag_list = tag_list.map { |tag| tag.gsub(" ", " ").gsub(" ", ", ") } end def save_tagger @@ -78,7 +78,7 @@ def get_title_from_url(url) # TODO: 日本語以外 # charsets = ['iso-2022-jp', 'euc-jp', 'shift_jis', 'iso-8859-1'] # if charsets.include?(page.charset.downcase) - title = NKF.nkf('-w', CGI.unescapeHTML((doc.at("title").inner_text))).to_s.gsub(/\r\n|\r|\n/, '').gsub(/\s+/, ' ').strip + title = NKF.nkf("-w", CGI.unescapeHTML((doc.at("title").inner_text))).to_s.gsub(/\r\n|\r|\n/, "").gsub(/\s+/, " ").strip if title.blank? title = url end @@ -95,7 +95,7 @@ def get_title_from_url(url) def self.get_canonical_url(url) doc = Nokogiri::HTML(Faraday.get(url).body) - canonical_url = doc.search("/html/head/link[@rel='canonical']").first['href'] + canonical_url = doc.search("/html/head/link[@rel='canonical']").first["href"] # TODO: URLを相対指定している時 Addressable::URI.parse(canonical_url).normalize.to_s rescue @@ -111,10 +111,10 @@ def my_host_resource def bookmarkable_url? if url.try(:my_host?) unless url.try(:bookmarkable_id) - errors.add(:base, I18n.t('bookmark.not_our_holding')) + errors.add(:base, I18n.t("bookmark.not_our_holding")) end unless my_host_resource - errors.add(:base, I18n.t('bookmark.not_our_holding')) + errors.add(:base, I18n.t("bookmark.not_our_holding")) end end end @@ -131,7 +131,7 @@ def get_manifestation def already_bookmarked? if manifestation if manifestation.bookmarked?(user) - errors.add(:base, 'already_bookmarked') + errors.add(:base, "already_bookmarked") end end end @@ -143,7 +143,7 @@ def create_manifestation return end manifestation = Manifestation.new(access_address: url) - manifestation.carrier_type = CarrierType.find_by(name: 'online_resource') + manifestation.carrier_type = CarrierType.find_by(name: "online_resource") if title.present? manifestation.original_title = title else @@ -156,12 +156,12 @@ def create_manifestation item.shelf = Shelf.web item.manifestation = manifestation if defined?(EnjuCirculation) - item.circulation_status = CirculationStatus.where(name: 'Not Available').first + item.circulation_status = CirculationStatus.where(name: "Not Available").first end item.save! if defined?(EnjuCirculation) - item.use_restriction = UseRestriction.where(name: 'Not For Loan').first + item.use_restriction = UseRestriction.where(name: "Not For Loan").first end end end @@ -177,7 +177,7 @@ def self.manifestations_count(start_date, end_date, manifestation) def tag_index! manifestation.reload manifestation.index - taggings.map{|tagging| Tag.find(tagging.tag_id).index} + taggings.map { |tagging| Tag.find(tagging.tag_id).index } Sunspot.commit end end diff --git a/app/models/bookmark_stat.rb b/app/models/bookmark_stat.rb index 669c02d4bb..9963c1ec80 100644 --- a/app/models/bookmark_stat.rb +++ b/app/models/bookmark_stat.rb @@ -4,8 +4,8 @@ class BookmarkStat < ApplicationRecord initial_state: UserCheckoutStatStateMachine.initial_state ] include CalculateStat - default_scope { order('bookmark_stats.id DESC') } - scope :not_calculated, -> {in_state(:pending)} + default_scope { order("bookmark_stats.id DESC") } + scope :not_calculated, -> { in_state(:pending) } has_many :bookmark_stat_has_manifestations, dependent: :destroy has_many :manifestations, through: :bookmark_stat_has_manifestations @@ -27,7 +27,7 @@ def calculate_count! # manifestation.update_attributes({:daily_bookmarks_count => daily_count, :total_count => manifestation.total_count + daily_count}) if daily_count > 0 self.manifestations << manifestation - sql = ['UPDATE bookmark_stat_has_manifestations SET bookmarks_count = ? WHERE bookmark_stat_id = ? AND manifestation_id = ?', daily_count, self.id, manifestation.id] + sql = [ "UPDATE bookmark_stat_has_manifestations SET bookmarks_count = ? WHERE bookmark_stat_id = ? AND manifestation_id = ?", daily_count, self.id, manifestation.id ] ActiveRecord::Base.connection.execute( self.class.send(:sanitize_sql_array, sql) ) diff --git a/app/models/bookmark_stat_transition.rb b/app/models/bookmark_stat_transition.rb index 5ae1a68079..84313a0c08 100644 --- a/app/models/bookmark_stat_transition.rb +++ b/app/models/bookmark_stat_transition.rb @@ -1,7 +1,4 @@ class BookmarkStatTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :bookmark_stat, inverse_of: :bookmark_stat_transitions end @@ -11,7 +8,7 @@ class BookmarkStatTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # bookmark_stat_id :bigint # created_at :datetime not null diff --git a/app/models/bookstore.rb b/app/models/bookstore.rb index 2e538b0a28..645da90d6c 100644 --- a/app/models/bookstore.rb +++ b/app/models/bookstore.rb @@ -1,5 +1,5 @@ class Bookstore < ApplicationRecord - default_scope { order('bookstores.position') } + default_scope { order("bookstores.position") } has_many :items, dependent: :restrict_with_exception acts_as_list diff --git a/app/models/carrier_type.rb b/app/models/carrier_type.rb index 90f7162c7f..86019632f6 100644 --- a/app/models/carrier_type.rb +++ b/app/models/carrier_type.rb @@ -5,18 +5,18 @@ class CarrierType < ApplicationRecord has_one_attached :attachment before_save do - attachment.purge if delete_attachment == '1' + attachment.purge if delete_attachment == "1" end attr_accessor :delete_attachment def mods_type case name - when 'volume' - 'text' + when "volume" + "text" else # TODO: その他のタイプ - 'software, multimedia' + "software, multimedia" end end end diff --git a/app/models/carrier_type_has_checkout_type.rb b/app/models/carrier_type_has_checkout_type.rb index dc95470d1f..9ed7f3fa42 100644 --- a/app/models/carrier_type_has_checkout_type.rb +++ b/app/models/carrier_type_has_checkout_type.rb @@ -1,6 +1,6 @@ class CarrierTypeHasCheckoutType < ApplicationRecord - scope :available_for_carrier_type, lambda {|carrier_type| includes(:carrier_type).where('carrier_types.name = ?', carrier_type.name)} - scope :available_for_user_group, lambda {|user_group| includes(checkout_type: :user_groups).where('user_groups.name = ?', user_group.name)} + scope :available_for_carrier_type, lambda { |carrier_type| includes(:carrier_type).where("carrier_types.name = ?", carrier_type.name) } + scope :available_for_user_group, lambda { |user_group| includes(checkout_type: :user_groups).where("user_groups.name = ?", user_group.name) } belongs_to :carrier_type belongs_to :checkout_type diff --git a/app/models/checked_item.rb b/app/models/checked_item.rb index a65869d028..7090d3b8ab 100644 --- a/app/models/checked_item.rb +++ b/app/models/checked_item.rb @@ -1,13 +1,13 @@ class CheckedItem < ApplicationRecord belongs_to :item, optional: true belongs_to :basket - belongs_to :librarian, class_name: 'User', optional: true + belongs_to :librarian, class_name: "User", optional: true validates_associated :item, :basket, on: :update validates :item, :basket, :due_date, presence: { on: :update } validates :item_id, uniqueness: { scope: :basket_id } validate :available_for_checkout?, on: :create - validates :due_date_string, format: {with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/}, allow_blank: true + validates :due_date_string, format: { with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/ }, allow_blank: true validate :check_due_date before_validation :set_item @@ -19,29 +19,29 @@ class CheckedItem < ApplicationRecord def available_for_checkout? if item.blank? - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.item_not_found')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.item_not_found")) return false end if item.rent? - unless item.circulation_status.name == 'Missing' - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.already_checked_out')) + unless item.circulation_status.name == "Missing" + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.already_checked_out")) end end unless item.available_for_checkout? - if item.circulation_status.name == 'Missing' - item.circulation_status = CirculationStatus.find_by(name: 'Available On Shelf') + if item.circulation_status.name == "Missing" + item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf") item.save set_due_date else - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.not_available_for_checkout')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.not_available_for_checkout")) return false end end if item_checkout_type.blank? - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.this_group_cannot_checkout')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.this_group_cannot_checkout")) return false end # ここまでは絶対に貸出ができない場合 @@ -49,19 +49,19 @@ def available_for_checkout? return true if ignore_restriction == "1" if item.not_for_loan? - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.not_available_for_checkout')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.not_available_for_checkout")) end if item.reserved? unless item.manifestation.next_reservation.user == basket.user - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.reserved_item_included')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.reserved_item_included")) end end checkout_count = basket.user.checked_item_count checkout_type = item_checkout_type.checkout_type if checkout_count[:"#{checkout_type.name}"] >= item_checkout_type.checkout_limit - errors.add(:base, I18n.t('activerecord.errors.messages.checked_item.excessed_checkout_limit')) + errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.excessed_checkout_limit")) end if errors[:base].empty? diff --git a/app/models/checkin.rb b/app/models/checkin.rb index 0d6d0b7ff1..b8eea3e95a 100644 --- a/app/models/checkin.rb +++ b/app/models/checkin.rb @@ -1,9 +1,9 @@ class Checkin < ApplicationRecord - default_scope { order('checkins.id DESC') } - scope :on, lambda {|date| where('created_at >= ? AND created_at < ?', date.beginning_of_day, date.tomorrow.beginning_of_day)} + default_scope { order("checkins.id DESC") } + scope :on, lambda { |date| where("created_at >= ? AND created_at < ?", date.beginning_of_day, date.tomorrow.beginning_of_day) } has_one :checkout belongs_to :item, touch: true - belongs_to :librarian, class_name: 'User' + belongs_to :librarian, class_name: "User" belongs_to :basket validates :item_id, uniqueness: { scope: :basket_id } @@ -20,17 +20,17 @@ def available_for_checkin? end if item.blank? - errors.add(:base, I18n.t('checkin.item_not_found')) + errors.add(:base, I18n.t("checkin.item_not_found")) return end - if basket.items.find_by('item_id = ?', item.id) - errors[:base] << I18n.t('checkin.already_checked_in') + if basket.items.find_by("item_id = ?", item.id) + errors[:base] << I18n.t("checkin.already_checked_in") end end def item_checkin(current_user) - message = '' + message = "" Checkin.transaction do item.checkin! Checkout.not_returned.where(item_id: item_id).find_each do |checkout| @@ -42,22 +42,22 @@ def item_checkin(current_user) end checkout.save(validate: false) unless checkout.item.shelf.library == current_user.profile.library - message << I18n.t('checkin.other_library_item') + message << I18n.t("checkin.other_library_item") end end if item.reserved? # TODO: もっと目立たせるために別画面を表示するべき? - message << I18n.t('item.this_item_is_reserved') + message << I18n.t("item.this_item_is_reserved") item.retain(current_user) end if item.include_supplements? - message << I18n.t('item.this_item_include_supplement') + message << I18n.t("item.this_item_include_supplement") end - if item.circulation_status.name == 'Missing' - message << I18n.t('checkout.missing_item_found') + if item.circulation_status.name == "Missing" + message << I18n.t("checkout.missing_item_found") end # メールとメッセージの送信 diff --git a/app/models/checkout.rb b/app/models/checkout.rb index 2cbbe650dd..8e23fd735a 100644 --- a/app/models/checkout.rb +++ b/app/models/checkout.rb @@ -1,16 +1,16 @@ class Checkout < ApplicationRecord scope :not_returned, -> { where(checkin_id: nil) } scope :returned, -> { where.not(checkin_id: nil) } - scope :overdue, lambda {|date| where('checkin_id IS NULL AND due_date < ?', date)} - scope :due_date_on, lambda {|date| where(checkin_id: nil, due_date: date.beginning_of_day .. date.end_of_day)} - scope :completed, lambda {|start_date, end_date| where('checkouts.created_at >= ? AND checkouts.created_at < ?', start_date, end_date)} - scope :on, lambda {|date| where('created_at >= ? AND created_at < ?', date.beginning_of_day, date.tomorrow.beginning_of_day)} + scope :overdue, lambda { |date| where("checkin_id IS NULL AND due_date < ?", date) } + scope :due_date_on, lambda { |date| where(checkin_id: nil, due_date: date.beginning_of_day .. date.end_of_day) } + scope :completed, lambda { |start_date, end_date| where("checkouts.created_at >= ? AND checkouts.created_at < ?", start_date, end_date) } + scope :on, lambda { |date| where("created_at >= ? AND created_at < ?", date.beginning_of_day, date.tomorrow.beginning_of_day) } belongs_to :user, optional: true delegate :username, :user_number, to: :user, prefix: true belongs_to :item, touch: true belongs_to :checkin, optional: true - belongs_to :librarian, class_name: 'User' + belongs_to :librarian, class_name: "User" belongs_to :basket belongs_to :shelf, optional: true belongs_to :library, optional: true @@ -18,7 +18,7 @@ class Checkout < ApplicationRecord # TODO: 貸出履歴を保存しない場合は、ユーザ名を削除する # validates :user, :item, :basket, presence: true validates :due_date, date: true, presence: true - validates :item_id, uniqueness: { scope: [:basket_id, :user_id] } + validates :item_id, uniqueness: { scope: [ :basket_id, :user_id ] } validate :is_not_checked?, on: :create validate :renewable?, on: :update before_update :set_new_due_date @@ -50,7 +50,7 @@ class Checkout < ApplicationRecord def is_not_checked? checkout = Checkout.not_returned.where(item_id: item_id) unless checkout.empty? - errors.add(:base, I18n.t('activerecord.errors.messages.checkin.already_checked_out')) + errors.add(:base, I18n.t("activerecord.errors.messages.checkin.already_checked_out")) end end @@ -59,13 +59,13 @@ def renewable? messages = [] if !operator && overdue? - messages << I18n.t('checkout.you_have_overdue_item') + messages << I18n.t("checkout.you_have_overdue_item") end if !operator && reserved? - messages << I18n.t('checkout.this_item_is_reserved') + messages << I18n.t("checkout.this_item_is_reserved") end if !operator && over_checkout_renewal_limit? - messages << I18n.t('checkout.excessed_renewal_limit') + messages << I18n.t("checkout.excessed_renewal_limit") end if messages.empty? true @@ -150,7 +150,7 @@ def self.manifestations_count(start_date, end_date, manifestation) arel_table[:created_at].lt end_date ) .where( - item_id: manifestation.items.pluck('items.id') + item_id: manifestation.items.pluck("items.id") ).count end diff --git a/app/models/checkout_type.rb b/app/models/checkout_type.rb index e0e770df3e..5a53504496 100644 --- a/app/models/checkout_type.rb +++ b/app/models/checkout_type.rb @@ -1,7 +1,7 @@ class CheckoutType < ApplicationRecord include MasterModel - scope :available_for_carrier_type, lambda {|carrier_type| includes(:carrier_types).where('carrier_types.name = ?', carrier_type.name).order('carrier_types.position')} - scope :available_for_user_group, lambda {|user_group| includes(:user_groups).where('user_groups.name = ?', user_group.name).order('user_group.position')} + scope :available_for_carrier_type, lambda { |carrier_type| includes(:carrier_types).where("carrier_types.name = ?", carrier_type.name).order("carrier_types.position") } + scope :available_for_user_group, lambda { |user_group| includes(:user_groups).where("user_groups.name = ?", user_group.name).order("user_group.position") } has_many :user_group_has_checkout_types, dependent: :destroy has_many :user_groups, through: :user_group_has_checkout_types diff --git a/app/models/cinii_book.rb b/app/models/cinii_book.rb index 82f0738ed0..69c1bb77b1 100644 --- a/app/models/cinii_book.rb +++ b/app/models/cinii_book.rb @@ -4,30 +4,30 @@ def initialize(node) end def title - @node.at('./xmlns:title').try(:content) + @node.at("./xmlns:title").try(:content) end def creator - @node.at('./dc:creator').try(:content) + @node.at("./dc:creator").try(:content) end def publisher - @node.at('./dc:publisher').try(:content) + @node.at("./dc:publisher").try(:content) end def link - @node.at('./xmlns:link').try(:content) + @node.at("./xmlns:link").try(:content) end def ncid - url = @node.attributes['about'].try(:content) + url = @node.attributes["about"].try(:content) if url - URI.parse(url).path.split('/').reverse.first + URI.parse(url).path.split("/").reverse.first end end def issued - @node.at('./dc:date').try(:content) + @node.at("./dc:date").try(:content) end def self.per_page @@ -38,13 +38,13 @@ def self.search(query, page = 1, per_page = self.per_page) if query cnt = self.per_page page = 1 if page.to_i < 1 - doc = Nokogiri::XML(Manifestation.search_cinii_book(query, {p: page, count: cnt, raw: true}).to_s) - items = doc.xpath('//xmlns:item').collect{|node| self.new node } - total_entries = doc.at('//opensearch:totalResults').content.to_i + doc = Nokogiri::XML(Manifestation.search_cinii_book(query, { p: page, count: cnt, raw: true }).to_s) + items = doc.xpath("//xmlns:item").collect { |node| self.new node } + total_entries = doc.at("//opensearch:totalResults").content.to_i - {items: items, total_entries: total_entries} + { items: items, total_entries: total_entries } else - {items: [], total_entries: 0} + { items: [], total_entries: 0 } end end diff --git a/app/models/circulation_status.rb b/app/models/circulation_status.rb index f59ef79676..66dff2c196 100644 --- a/app/models/circulation_status.rb +++ b/app/models/circulation_status.rb @@ -2,8 +2,8 @@ class CirculationStatus < ApplicationRecord include MasterModel validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ } - default_scope { order('circulation_statuses.position') } - scope :available_for_checkout, -> { where(name: 'Available On Shelf') } + default_scope { order("circulation_statuses.position") } + scope :available_for_checkout, -> { where(name: "Available On Shelf") } has_many :items, dependent: :restrict_with_exception private diff --git a/app/models/classification.rb b/app/models/classification.rb index f4f784bae7..73b4ed20b9 100644 --- a/app/models/classification.rb +++ b/app/models/classification.rb @@ -7,7 +7,7 @@ class Classification < ApplicationRecord text :category, :note integer :classification_type_id end - strip_attributes only: [:category, :url] + strip_attributes only: [ :category, :url ] paginates_per 10 end diff --git a/app/models/concerns/bookmark_url.rb b/app/models/concerns/bookmark_url.rb index d8b8c1104b..a6c74a6936 100644 --- a/app/models/concerns/bookmark_url.rb +++ b/app/models/concerns/bookmark_url.rb @@ -5,7 +5,7 @@ def my_host? raise ::Addressable::URI::InvalidURIError end config_url = ::Addressable::URI.parse(LibraryGroup.site_config.url) - if url.host == config_url.host and url.port == config_url.port and ['http', 'https'].include?(url.scheme) + if url.host == config_url.host and url.port == config_url.port and [ "http", "https" ].include?(url.scheme) true else false diff --git a/app/models/concerns/calculate_stat.rb b/app/models/concerns/calculate_stat.rb index e4556facdb..9789234731 100644 --- a/app/models/concerns/calculate_stat.rb +++ b/app/models/concerns/calculate_stat.rb @@ -25,7 +25,7 @@ def check_date # 利用統計の集計完了メッセージを送信します。 def send_message(mailer) - sender = User.find(1) #system + sender = User.find(1) # system message = Message.create!( recipient: user.username, sender: sender, diff --git a/app/models/concerns/enju_bookmark/enju_manifestation.rb b/app/models/concerns/enju_bookmark/enju_manifestation.rb index e29e7a917d..4a2549a944 100644 --- a/app/models/concerns/enju_bookmark/enju_manifestation.rb +++ b/app/models/concerns/enju_bookmark/enju_manifestation.rb @@ -8,10 +8,10 @@ module EnjuManifestation searchable do string :tag, multiple: true do - bookmarks.map{|bookmark| bookmark.tag_list}.flatten + bookmarks.map { |bookmark| bookmark.tag_list }.flatten end text :tag do - bookmarks.map{|bookmark| bookmark.tag_list}.flatten + bookmarks.map { |bookmark| bookmark.tag_list }.flatten end end end @@ -22,7 +22,7 @@ def bookmarked?(user) end def tags - bookmarks.map{|bookmark| bookmark.tags}.flatten + bookmarks.map { |bookmark| bookmark.tags }.flatten end end end diff --git a/app/models/concerns/enju_circulation/enju_accept.rb b/app/models/concerns/enju_circulation/enju_accept.rb index e85702b62f..089f4d128a 100644 --- a/app/models/concerns/enju_circulation/enju_accept.rb +++ b/app/models/concerns/enju_circulation/enju_accept.rb @@ -10,8 +10,8 @@ module EnjuAccept end def accept! - item.circulation_status = CirculationStatus.find_by(name: 'Available On Shelf') - item.use_restriction = UseRestriction.find_by(name: 'Limited Circulation, Normal Loan Period') + item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf") + item.use_restriction = UseRestriction.find_by(name: "Limited Circulation, Normal Loan Period") end end end diff --git a/app/models/concerns/enju_circulation/enju_basket.rb b/app/models/concerns/enju_circulation/enju_basket.rb index 208ffcc74a..ef1a3331a5 100644 --- a/app/models/concerns/enju_circulation/enju_basket.rb +++ b/app/models/concerns/enju_circulation/enju_basket.rb @@ -14,7 +14,9 @@ def basket_checkout(librarian) Item.transaction do checked_items.each do |checked_item| - checkout = user.checkouts.new( + checked_item.item.reload + + checkout = user.checkouts.create!( librarian: librarian, item: checked_item.item, basket: self, @@ -22,7 +24,6 @@ def basket_checkout(librarian) shelf: checked_item.item.shelf, due_date: checked_item.due_date ) - checkout.save! checked_item.item.checkout!(user) end CheckedItem.where(basket_id: id).destroy_all diff --git a/app/models/concerns/enju_circulation/enju_item.rb b/app/models/concerns/enju_circulation/enju_item.rb index 5b5ffec57c..d8052885bc 100644 --- a/app/models/concerns/enju_circulation/enju_item.rb +++ b/app/models/concerns/enju_circulation/enju_item.rb @@ -4,27 +4,27 @@ module EnjuItem included do FOR_CHECKOUT_CIRCULATION_STATUS = [ - 'Available On Shelf', - 'On Loan', - 'Waiting To Be Reshelved' + "Available On Shelf", + "On Loan", + "Waiting To Be Reshelved" ] FOR_CHECKOUT_USE_RESTRICTION = [ - 'Available For Supply Without Return', - 'Limited Circulation, Long Loan Period', - 'Limited Circulation, Short Loan Period', - 'No Reproduction', - 'Overnight Only', - 'Renewals Not Permitted', - 'Supervision Required', - 'Term Loan', - 'User Signature Required', - 'Limited Circulation, Normal Loan Period' + "Available For Supply Without Return", + "Limited Circulation, Long Loan Period", + "Limited Circulation, Short Loan Period", + "No Reproduction", + "Overnight Only", + "Renewals Not Permitted", + "Supervision Required", + "Term Loan", + "User Signature Required", + "Limited Circulation, Normal Loan Period" ] - scope :for_checkout, ->(identifier_conditions = 'item_identifier IS NOT NULL') { + scope :for_checkout, ->(identifier_conditions = "item_identifier IS NOT NULL") { includes(:circulation_status, :use_restriction).where( - 'circulation_statuses.name' => FOR_CHECKOUT_CIRCULATION_STATUS, - 'use_restrictions.name' => FOR_CHECKOUT_USE_RESTRICTION + "circulation_statuses.name" => FOR_CHECKOUT_CIRCULATION_STATUS, + "use_restrictions.name" => FOR_CHECKOUT_USE_RESTRICTION ).where(identifier_conditions) } @@ -48,14 +48,14 @@ module EnjuItem end def set_circulation_status - self.circulation_status = CirculationStatus.find_by(name: 'In Process') if circulation_status.nil? + self.circulation_status = CirculationStatus.find_by(name: "In Process") if circulation_status.nil? end def check_circulation_status - return unless circulation_status.name == 'Removed' + return unless circulation_status.name == "Removed" - errors.add(:base, I18n.t('activerecord.errors.models.item.attributes.circulation_status_id.is_rented')) if rented? - errors.add(:base, I18n.t('activerecord.errors.models.item.attributes.circulation_status_id.is_reserved')) if reserved? + errors.add(:base, I18n.t("activerecord.errors.models.item.attributes.circulation_status_id.is_rented")) if rented? + errors.add(:base, I18n.t("activerecord.errors.models.item.attributes.circulation_status_id.is_reserved")) if reserved? end def checkout_status(user) @@ -71,7 +71,7 @@ def reserved? end def rent? - return true if checkouts.not_returned.select(:item_id).detect{|checkout| checkout.item_id == id} + return true if checkouts.not_returned.select(:item_id).detect { |checkout| checkout.item_id == id } false end @@ -80,15 +80,12 @@ def rented? rent? end - def reserved_by_user?(user) - if manifestation.next_reservation - return true if manifestation.next_reservation.user == user - end - false + def user_reservation(user) + user.reserves.waiting.order("reserves.created_at").find_by(manifestation: manifestation) end def available_for_checkout? - if circulation_status.name == 'On Loan' + if circulation_status.name == "On Loan" false else manifestation.items.for_checkout.include?(self) @@ -96,18 +93,19 @@ def available_for_checkout? end def checkout!(user) - if reserved_by_user?(user) - manifestation.next_reservation.update(checked_out_at: Time.zone.now) - manifestation.next_reservation.transition_to!(:completed) - manifestation.reload - end + Item.transaction do + reserve = user_reservation(user) + if reserve && !reserve.state_machine.in_state?(:completed) + reserve.checked_out_at = Time.zone.now + reserve.state_machine.transition_to!(:completed) + end - reload - update!(circulation_status: CirculationStatus.find_by(name: 'On Loan')) + update!(circulation_status: CirculationStatus.find_by(name: "On Loan")) + end end def checkin! - self.circulation_status = CirculationStatus.find_by(name: 'Available On Shelf') + self.circulation_status = CirculationStatus.find_by(name: "Available On Shelf") save! end diff --git a/app/models/concerns/enju_circulation/enju_manifestation.rb b/app/models/concerns/enju_circulation/enju_manifestation.rb index 6125634d5b..7e9e18e3ea 100644 --- a/app/models/concerns/enju_circulation/enju_manifestation.rb +++ b/app/models/concerns/enju_circulation/enju_manifestation.rb @@ -13,7 +13,7 @@ module EnjuManifestation end def next_reservation - reserves.waiting.order('reserves.created_at ASC').readonly(false).first + reserves.waiting.not_in_state(:retained).order("reserves.created_at ASC").readonly(false).first end def available_checkout_types(user) @@ -26,7 +26,7 @@ def is_reservable_by?(user) return false if items.for_checkout.empty? return false unless user - unless user.has_role?('Librarian') + unless user.has_role?("Librarian") unless items.size == (items.size - user.checkouts.overdue(Time.zone.now).collect(&:item).size) return false end diff --git a/app/models/concerns/enju_circulation/enju_user.rb b/app/models/concerns/enju_circulation/enju_user.rb index 549d8c7729..a1c62fc7bb 100644 --- a/app/models/concerns/enju_circulation/enju_user.rb +++ b/app/models/concerns/enju_circulation/enju_user.rb @@ -18,7 +18,7 @@ module EnjuUser def check_item_before_destroy # TODO: 貸出記録を残す場合 if checkouts.size.positive? - raise 'This user has items still checked out.' + raise "This user has items still checked out." end end @@ -26,13 +26,13 @@ def checked_item_count checkout_count = {} CheckoutType.find_each do |checkout_type| # 資料種別ごとの貸出中の冊数を計算 - checkout_count[:"#{checkout_type.name}"] = checkouts.count_by_sql([" + checkout_count[:"#{checkout_type.name}"] = checkouts.count_by_sql([ " SELECT count(item_id) FROM checkouts WHERE item_id IN ( SELECT id FROM items WHERE checkout_type_id = ? ) - AND user_id = ? AND checkin_id IS NULL", checkout_type.id, id] + AND user_id = ? AND checkin_id IS NULL", checkout_type.id, id ] ) end checkout_count diff --git a/app/models/concerns/enju_circulation/enju_withdraw.rb b/app/models/concerns/enju_circulation/enju_withdraw.rb index 44140bb58b..c02813c812 100644 --- a/app/models/concerns/enju_circulation/enju_withdraw.rb +++ b/app/models/concerns/enju_circulation/enju_withdraw.rb @@ -8,9 +8,9 @@ module EnjuWithdraw end def withdraw! - circulation_status = CirculationStatus.find_by(name: 'Removed') + circulation_status = CirculationStatus.find_by(name: "Removed") item.update_column(:circulation_status_id, circulation_status.id) if circulation_status - item.use_restriction = UseRestriction.find_by(name: 'Not For Loan') + item.use_restriction = UseRestriction.find_by(name: "Not For Loan") item.index! end diff --git a/app/models/concerns/enju_event/enju_library.rb b/app/models/concerns/enju_event/enju_library.rb index 491df211aa..719aee6ba3 100644 --- a/app/models/concerns/enju_event/enju_library.rb +++ b/app/models/concerns/enju_event/enju_library.rb @@ -7,7 +7,7 @@ module EnjuLibrary end def closed?(date) - events.closing_days.map{ |c| + events.closing_days.map { |c| c.start_at.beginning_of_day }.include?(date.beginning_of_day) end diff --git a/app/models/concerns/enju_inventory/enju_item.rb b/app/models/concerns/enju_inventory/enju_item.rb index 3e8efe8d11..0880d59e65 100644 --- a/app/models/concerns/enju_inventory/enju_item.rb +++ b/app/models/concerns/enju_inventory/enju_item.rb @@ -9,13 +9,13 @@ module EnjuItem integer :inventory_file_ids, multiple: true end - def self.inventory_items(inventory_file, mode = 'not_on_shelf') + def self.inventory_items(inventory_file, mode = "not_on_shelf") item_ids = Item.pluck(:id) - inventory_item_ids = inventory_file.items.pluck('items.id') + inventory_item_ids = inventory_file.items.pluck("items.id") case mode - when 'not_on_shelf' + when "not_on_shelf" Item.where(id: (item_ids - inventory_item_ids)) - when 'not_in_catalog' + when "not_in_catalog" Item.where(id: (inventory_item_ids - item_ids)) end rescue StandardError diff --git a/app/models/concerns/enju_library/enju_item.rb b/app/models/concerns/enju_library/enju_item.rb index 2079aa4ea1..86362a7077 100644 --- a/app/models/concerns/enju_library/enju_item.rb +++ b/app/models/concerns/enju_library/enju_item.rb @@ -4,7 +4,7 @@ module EnjuItem included do has_one :accept - scope :accepted_between, lambda{|from, to| includes(:accept).where('items.created_at BETWEEN ? AND ?', Time.zone.parse(from).beginning_of_day, Time.zone.parse(to).end_of_day)} + scope :accepted_between, lambda { |from, to| includes(:accept).where("items.created_at BETWEEN ? AND ?", Time.zone.parse(from).beginning_of_day, Time.zone.parse(to).end_of_day) } belongs_to :shelf, counter_cache: true diff --git a/app/models/concerns/enju_loc/enju_manifestation.rb b/app/models/concerns/enju_loc/enju_manifestation.rb index 1563927903..b4c7ddc0bc 100644 --- a/app/models/concerns/enju_loc/enju_manifestation.rb +++ b/app/models/concerns/enju_loc/enju_manifestation.rb @@ -18,11 +18,11 @@ def self.loc_search(query, options = {}) end def self.import_record_from_loc_isbn(options) - #if options[:isbn] + # if options[:isbn] lisbn = Lisbn.new(options[:isbn]) raise EnjuLoc::InvalidIsbn unless lisbn.valid? - #end + # end manifestation = Manifestation.find_by_isbn(lisbn.isbn) return manifestation.first if manifestation.present? @@ -33,19 +33,19 @@ def self.import_record_from_loc_isbn(options) import_record_from_loc(doc) end - NS = {"mods" => "http://www.loc.gov/mods/v3"} + NS = { "mods" => "http://www.loc.gov/mods/v3" } def self.import_record_from_loc(doc) - record_identifier = doc.at('//mods:recordInfo/mods:recordIdentifier', NS).try(:content) - identifier_type = IdentifierType.find_by(name: 'loc_identifier') - identifier_type ||= IdentifierType.create!(name: 'loc_identifier') + record_identifier = doc.at("//mods:recordInfo/mods:recordIdentifier", NS).try(:content) + identifier_type = IdentifierType.find_by(name: "loc_identifier") + identifier_type ||= IdentifierType.create!(name: "loc_identifier") loc_identifier = Identifier.find_by(body: record_identifier, identifier_type_id: identifier_type.id) return loc_identifier.manifestation if loc_identifier publishers = [] - doc.xpath('//mods:publisher', NS).each do |publisher| + doc.xpath("//mods:publisher", NS).each do |publisher| publishers << { full_name: publisher.content, - #:agent_identifier => publisher.attributes["about"].try(:content) + # :agent_identifier => publisher.attributes["about"].try(:content) } end @@ -73,13 +73,13 @@ def self.import_record_from_loc(doc) content_type = types[:content_type] carrier_type = types[:carrier_type] - record_identifier = doc.at('//mods:recordInfo/mods:recordIdentifier', NS).try(:content) - description = doc.xpath('//mods:abstract', NS).collect(&:content).join("\n") - edition_string = doc.at('//mods:edition', NS).try(:content) + record_identifier = doc.at("//mods:recordInfo/mods:recordIdentifier", NS).try(:content) + description = doc.xpath("//mods:abstract", NS).collect(&:content).join("\n") + edition_string = doc.at("//mods:edition", NS).try(:content) extent = get_mods_extent(doc) note = get_mods_note(doc) frequency = get_mods_frequency(doc) - issuance = doc.at('//mods:issuance', NS).try(:content) + issuance = doc.at("//mods:issuance", NS).try(:content) is_serial = true if issuance == "serial" statement_of_responsibility = get_mods_statement_of_responsibility(doc) access_address = get_mods_access_address(doc) @@ -114,14 +114,14 @@ def self.import_record_from_loc(doc) identifier[:loc_identifier] = Identifier.new( manifestation: manifestation, body: loc_identifier, - identifier_type: IdentifierType.find_by(name: 'loc_identifier') || IdentifierType.create!(name: 'loc_identifier') + identifier_type: IdentifierType.find_by(name: "loc_identifier") || IdentifierType.create!(name: "loc_identifier") ) end if issn_l identifier[:issn_l] = Identifier.new( manifestation: manifestation, body: issn_l, - identifier_type: IdentifierType.find_by(name: 'issn_l') || IdentifierType.create!(name: 'issn_l') + identifier_type: IdentifierType.find_by(name: "issn_l") || IdentifierType.create!(name: "issn_l") ) end @@ -152,18 +152,18 @@ def self.create_loc_subject_related_elements(doc, manifestation) subjects = get_mods_subjects(doc) classifications = get_mods_classifications(doc) if defined?(EnjuSubject) - subject_heading_type = SubjectHeadingType.find_by(name: 'lcsh') || SubjectHeadingType.create!(name: 'lcsh') + subject_heading_type = SubjectHeadingType.find_by(name: "lcsh") || SubjectHeadingType.create!(name: "lcsh") subjects.each do |term| subject = Subject.find_by(term: term[:term]) unless subject subject = Subject.new(term) subject.subject_heading_type = subject_heading_type - subject.subject_type = SubjectType.find_by(name: 'concept') || SubjectType.create!(name: 'concept') + subject.subject_type = SubjectType.find_by(name: "concept") || SubjectType.create!(name: "concept") end manifestation.subjects << subject end if classifications - classification_type = ClassificationType.find_by(name: 'ddc') || ClassificationType.create!(name: 'ddc') + classification_type = ClassificationType.find_by(name: "ddc") || ClassificationType.create!(name: "ddc") classifications.each do |ddc| classification = Classification.find_by(category: ddc) unless classification @@ -180,7 +180,7 @@ def self.create_loc_series_statement(doc, manifestation) doc.xpath('//mods:relatedItem[@type="series"]/mods:titleInfo/mods:title', NS).each do |series| series_title = title = series.try(:content) if title - series_title = title.split(';')[0].strip + series_title = title.split(";")[0].strip end next unless series_title @@ -206,20 +206,20 @@ def self.create_loc_series_master(doc, manifestation) def self.get_mods_titles(doc) original_title = "" title_alternatives = [] - doc.xpath('//mods:mods/mods:titleInfo', NS).each do |e| + doc.xpath("//mods:mods/mods:titleInfo", NS).each do |e| type = e.attributes["type"].try(:content) case type when "alternative", "translated", "abbreviated", "uniform" - title_alternatives << e.at('./mods:title', NS).content + title_alternatives << e.at("./mods:title", NS).content else - nonsort = e.at('./mods:nonSort', NS).try(:content) + nonsort = e.at("./mods:nonSort", NS).try(:content) original_title << nonsort if nonsort - original_title << e.at('./mods:title', NS).try(:content) - subtitle = e.at('./mods:subTitle', NS).try(:content) + original_title << e.at("./mods:title", NS).try(:content) + subtitle = e.at("./mods:subTitle", NS).try(:content) original_title << " : #{subtitle}" if subtitle - partnumber = e.at('./mods:partNumber', NS).try(:content) - partname = e.at('./mods:partName', NS).try(:content) - partname = [partnumber, partname].compact.join(": ") + partnumber = e.at("./mods:partNumber", NS).try(:content) + partname = e.at("./mods:partName", NS).try(:content) + partname = [ partnumber, partname ].compact.join(": ") original_title << ". #{partname}" if partname.present? end end @@ -232,7 +232,7 @@ def self.get_mods_language(doc) def self.get_mods_access_address(doc) access_address = nil - url = doc.at('//mods:location/mods:url', NS) + url = doc.at("//mods:location/mods:url", NS) if url usage = url.attributes["usage"].try(:content) case usage @@ -248,10 +248,10 @@ def self.get_mods_publication_place(doc) end def self.get_mods_extent(doc) - extent = doc.at('//mods:extent', NS).try(:content) - value = {start_page: nil, end_page: nil, height: nil} + extent = doc.at("//mods:extent", NS).try(:content) + value = { start_page: nil, end_page: nil, height: nil } if extent - extent = extent.split(';') + extent = extent.split(";") page = extent[0].try(:strip) value[:extent] = page if page =~ /(\d+)\s*(p|page)/ @@ -270,15 +270,15 @@ def self.get_mods_extent(doc) def self.get_mods_statement_of_responsibility(doc) note = doc.at('//mods:note[@type="statement of responsibility"]', NS).try(:content) if note.blank? - note = get_mods_creators(doc).map{|e| e[:full_name] }.join(" ; ") + note = get_mods_creators(doc).map { |e| e[:full_name] }.join(" ; ") end note end def self.get_mods_note(doc) notes = [] - doc.xpath('//mods:note', NS).each do |note| - type = note.attributes['type'].try(:content) + doc.xpath("//mods:note", NS).each do |note| + type = note.attributes["type"].try(:content) next if type == "statement of responsibility" note_s = note.try(:content) @@ -293,11 +293,11 @@ def self.get_mods_note(doc) def self.get_mods_date_of_publication(doc) dates = [] - doc.xpath('//mods:dateIssued', NS).each do |pub_date| - pub_date = pub_date.content.sub(/\A[cp]/, '') + doc.xpath("//mods:dateIssued", NS).each do |pub_date| + pub_date = pub_date.content.sub(/\A[cp]/, "") next unless pub_date =~ /^\d+(-\d\d?){0,2}$/ - date = pub_date.split('-') + date = pub_date.split("-") if date[0] and date[1] dates << sprintf("%04d-%02d", date[0], date[1]) else @@ -329,7 +329,7 @@ def self.get_mods_date_of_publication(doc) ] def self.get_mods_frequency(doc) frequencies = [] - doc.xpath('//mods:frequency', NS).each do |freq| + doc.xpath("//mods:frequency", NS).each do |freq| frequency = freq.try(:content) MARCFREQUENCY.each do |freq_regex| if /\A(#{freq_regex})/ =~ frequency @@ -343,9 +343,9 @@ def self.get_mods_frequency(doc) def self.get_mods_creators(doc) creators = [] - doc.xpath('/mods:mods/mods:name', NS).each do |creator| + doc.xpath("/mods:mods/mods:name", NS).each do |creator| creators << { - full_name: creator.xpath('./mods:namePart', NS).collect(&:content).join(", ") + full_name: creator.xpath("./mods:namePart", NS).collect(&:content).join(", ") } end creators.uniq @@ -356,25 +356,25 @@ def self.get_mods_subjects(doc) subjects = [] doc.xpath('//mods:subject[@authority="lcsh"]', NS).each do |s| subject = [] - s.xpath('./*', NS).each do |subelement| + s.xpath("./*", NS).each do |subelement| type = subelement.name case subelement.name when "topic", "geographic", "genre", "temporal" subject << { type: type , term: subelement.try(:content) } when "titleInfo" - subject << { type: type, term: subelement.at('./mods:title', NS).try(:content) } + subject << { type: type, term: subelement.at("./mods:title", NS).try(:content) } when "name" - name = subelement.xpath('./mods:namePart', NS).map{|e| e.try(:content) }.join(", ") + name = subelement.xpath("./mods:namePart", NS).map { |e| e.try(:content) }.join(", ") subject << { type: type, term: name } end end next if subject.compact.empty? if subject.size > 1 and subject[0][:type] == "name" and subject[1][:type] == "titleInfo" - subject[0..1] = { term: subject[0..1].map{|e|e[:term]}.join(". ") } + subject[0..1] = { term: subject[0..1].map { |e|e[:term] }.join(". ") } end subjects << { - term: subject.map{|e|e[:term]}.compact.join("--") + term: subject.map { |e|e[:term] }.compact.join("--") } end subjects @@ -394,20 +394,20 @@ def self.get_mods_classifications(doc) def self.get_mods_carrier_and_content_types(doc) carrier_type = content_type = nil - doc.xpath('//mods:form', NS).each do |e| - authority = e.attributes['authority'].try(:content) + doc.xpath("//mods:form", NS).each do |e| + authority = e.attributes["authority"].try(:content) case authority when "gmd" case e.content when "electronic resource" - carrier_type = CarrierType.find_by(name: 'online_resource') + carrier_type = CarrierType.find_by(name: "online_resource") when "videorecording", "motion picture", "game" - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') + content_type = ContentType.find_by(name: "two_dimensional_moving_image") when "sound recording" - content_type = ContentType.find_by(name: 'performed_music') + content_type = ContentType.find_by(name: "performed_music") when "graphic", "picture" - content_type = ContentType.find_by(name: 'still_image') - #TODO: Enju needs more specific mappings... + content_type = ContentType.find_by(name: "still_image") + # TODO: Enju needs more specific mappings... when "art original", "microscope slides", "art reproduction", @@ -423,38 +423,38 @@ def self.get_mods_carrier_and_content_types(doc) "kit", "transparency", "microform" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") end when "marcsmd" # cf.http://www.loc.gov/standards/valuelist/marcsmd.html case e.content when "text", "large print", "regular print", "text in looseleaf binder" - carrier_type = CarrierType.find_by(name: 'volume') - content_type = ContentType.find_by(name: 'text') + carrier_type = CarrierType.find_by(name: "volume") + content_type = ContentType.find_by(name: "text") when "braille" - carrier_type = CarrierType.find_by(name: 'volume') - content_type = ContentType.find_by(name: 'tactile_text') + carrier_type = CarrierType.find_by(name: "volume") + content_type = ContentType.find_by(name: "tactile_text") when "videodisc" - carrier_type = CarrierType.find_by(name: 'videodisc') - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') + carrier_type = CarrierType.find_by(name: "videodisc") + content_type = ContentType.find_by(name: "two_dimensional_moving_image") when "videorecording", "videocartridge", "videocassette", "videoreel" - carrier_type = CarrierType.find_by(name: 'other') - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') + carrier_type = CarrierType.find_by(name: "other") + content_type = ContentType.find_by(name: "two_dimensional_moving_image") when "electronic resource" - carrier_type = CarrierType.find_by(name: 'online_resource') + carrier_type = CarrierType.find_by(name: "online_resource") when "chip cartridge", "computer optical disc cartridge", "magnetic disk", "magneto-optical disc", "optical disc", "remote", "tape cartridge", "tape cassette", "tape reel" - #carrier_type = CarrierType.find_by(name: 'other') + # carrier_type = CarrierType.find_by(name: 'other') when "motion picture", "film cartridge", "film cassette", "film reel" - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') + content_type = ContentType.find_by(name: "two_dimensional_moving_image") when "sound recording", "cylinder", "roll", "sound cartridge", "sound cassette", "sound-tape reel", "sound-track film", "wire recording" - content_type = ContentType.find_by(name: 'performed_music') + content_type = ContentType.find_by(name: "performed_music") when "sound disc" - content_type = ContentType.find_by(name: 'performed_music') - carrier_type = CarrierType.find_by(name: 'audio_disc') + content_type = ContentType.find_by(name: "performed_music") + carrier_type = CarrierType.find_by(name: "audio_disc") when "nonprojected graphic", "chart", "collage", "drawing", "flash card", "painting", "photomechanical print", "photonegative", "photoprint", "picture", "print", "technical drawing", "projected graphic", "filmslip", "filmstrip cartridge", "filmstrip roll", "other filmstrip type ", "slide", "transparency" - content_type = ContentType.find_by(name: 'still_image') + content_type = ContentType.find_by(name: "still_image") when "tactile material", "braille", "tactile, with no writing system" - content_type = ContentType.find_by(name: 'tactile_text') - #TODO: Enju needs more specific mappings... + content_type = ContentType.find_by(name: "tactile_text") + # TODO: Enju needs more specific mappings... when "globe", "celestial globe", "earth moon globe", @@ -479,55 +479,55 @@ def self.get_mods_carrier_and_content_types(doc) "microopaque", "combination", "moon" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") end when "marcform" # cf. http://www.loc.gov/standards/valuelist/marcform.html case e.content when "print", "large print" - carrier_type = CarrierType.find_by(name: 'volume') - content_type = ContentType.find_by(name: 'text') + carrier_type = CarrierType.find_by(name: "volume") + content_type = ContentType.find_by(name: "text") when "electronic" - carrier_type = CarrierType.find_by(name: 'online_resource') + carrier_type = CarrierType.find_by(name: "online_resource") when "braille" - content_type = ContentType.find_by(name: 'tactile_text') - #TODO: Enju needs more specific mappings... + content_type = ContentType.find_by(name: "tactile_text") + # TODO: Enju needs more specific mappings... when "microfiche", "microfilm" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") end end end - doc.xpath('//mods:genre', NS).each do |e| - authority = e.attributes['authority'].try(:content) + doc.xpath("//mods:genre", NS).each do |e| + authority = e.attributes["authority"].try(:content) case authority when "rdacontent" content_type = ContentType.find_by(name: e.content.gsub(/\W+/, "_")) - content_type ||= ContentType.find_by(name: 'other') + content_type ||= ContentType.find_by(name: "other") end end - type = doc.at('//mods:typeOfResource', NS).try(:content) + type = doc.at("//mods:typeOfResource", NS).try(:content) case type when "text" - content_type = ContentType.find_by(name: 'text') + content_type = ContentType.find_by(name: "text") when "sound recording" - content_type = ContentType.find_by(name: 'sounds') + content_type = ContentType.find_by(name: "sounds") when"sound recording-musical" - content_type = ContentType.find_by(name: 'performed_music') + content_type = ContentType.find_by(name: "performed_music") when"sound recording-nonmusical" - content_type = ContentType.find_by(name: 'spoken_word') + content_type = ContentType.find_by(name: "spoken_word") when "moving image" - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') + content_type = ContentType.find_by(name: "two_dimensional_moving_image") when "software, multimedia" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") when "cartographic " - content_type = ContentType.find_by(name: 'cartographic_image') + content_type = ContentType.find_by(name: "cartographic_image") when "notated music" - content_type = ContentType.find_by(name: 'notated_music') + content_type = ContentType.find_by(name: "notated_music") when "still image" - content_type = ContentType.find_by(name: 'still_image') + content_type = ContentType.find_by(name: "still_image") when "three dimensional object" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") when "mixed material" - content_type = ContentType.find_by(name: 'other') + content_type = ContentType.find_by(name: "other") end { carrier_type: carrier_type, content_type: content_type } end diff --git a/app/models/concerns/enju_manifestation_viewer/enju_manifestation.rb b/app/models/concerns/enju_manifestation_viewer/enju_manifestation.rb index 834b3d7a48..a4d522fa95 100644 --- a/app/models/concerns/enju_manifestation_viewer/enju_manifestation.rb +++ b/app/models/concerns/enju_manifestation_viewer/enju_manifestation.rb @@ -23,8 +23,8 @@ def nicovideo_id def flickr if access_address url = ::Addressable::URI.parse(access_address) - paths = url.path.split('/') - if url.host =~ /^www\.flickr\.com$/ && (paths[1] == 'photos') && paths[2] + paths = url.path.split("/") + if url.host =~ /^www\.flickr\.com$/ && (paths[1] == "photos") && paths[2] info = {} if paths[3] == "sets" info[:user] = paths[2] diff --git a/app/models/concerns/enju_message/enju_user.rb b/app/models/concerns/enju_message/enju_user.rb index 5822935b20..6a2bb7a8ea 100644 --- a/app/models/concerns/enju_message/enju_user.rb +++ b/app/models/concerns/enju_message/enju_user.rb @@ -3,8 +3,8 @@ module EnjuUser extend ActiveSupport::Concern included do - has_many :sent_messages, foreign_key: 'sender_id', class_name: 'Message', inverse_of: :sender, dependent: :nullify - has_many :received_messages, foreign_key: 'receiver_id', class_name: 'Message', inverse_of: :receiver, dependent: :nullify + has_many :sent_messages, foreign_key: "sender_id", class_name: "Message", inverse_of: :sender, dependent: :nullify + has_many :received_messages, foreign_key: "receiver_id", class_name: "Message", inverse_of: :receiver, dependent: :nullify end end end diff --git a/app/models/concerns/enju_ndl/enju_manifestation.rb b/app/models/concerns/enju_ndl/enju_manifestation.rb index b00f319978..26d00d999b 100644 --- a/app/models/concerns/enju_ndl/enju_manifestation.rb +++ b/app/models/concerns/enju_ndl/enju_manifestation.rb @@ -10,7 +10,7 @@ def import_isbn(isbn) def ndl_bib_doc(ndl_bib_id) url = "https://ndlsearch.ndl.go.jp/api/sru?operation=searchRetrieve&version=1.2&query=itemno=#{ndl_bib_id}&recordSchema=dcndl&onlyBib=true" - Nokogiri::XML(Nokogiri::XML(URI.parse(url).read).at('//xmlns:recordData').content) + Nokogiri::XML(Nokogiri::XML(URI.parse(url).read).at("//xmlns:recordData").content) end # Use http://www.ndl.go.jp/jp/dlib/standards/opendataset/aboutIDList.txt @@ -40,7 +40,7 @@ def import_from_ndl_search(options) end def import_record(doc) - iss_itemno = URI.parse(doc.at('//dcndl:BibAdminResource[@rdf:about]').values.first).path.split('/').last + iss_itemno = URI.parse(doc.at("//dcndl:BibAdminResource[@rdf:about]").values.first).path.split("/").last ndl_bib_id_record =NdlBibIdRecord.find_by(body: iss_itemno) return ndl_bib_id_record.manifestation if ndl_bib_id_record @@ -52,12 +52,12 @@ def import_record(doc) title = get_title(doc) # date of publication - pub_date = doc.at('//dcterms:issued').try(:content).to_s.tr('.', '-') + pub_date = doc.at("//dcterms:issued").try(:content).to_s.tr(".", "-") pub_date = nil unless pub_date =~ /^\d+(-\d{0,2}){0,2}$/ if pub_date - date = pub_date.split('-') + date = pub_date.split("-") date = if date[0] && date[1] - format('%04d-%02d', date[0], date[1]) + format("%04d-%02d", date[0], date[1]) else pub_date end @@ -76,37 +76,37 @@ def import_record(doc) carrier_type = content_type = nil is_serial = nil - doc.xpath('//dcndl:materialType[@rdf:resource]').each do |d| - case d.attributes['resource'].try(:content) - when 'http://ndl.go.jp/ndltype/Book' - carrier_type = CarrierType.find_by(name: 'print') - content_type = ContentType.find_by(name: 'text') - when 'http://ndl.go.jp/ndltype/Braille' - content_type = ContentType.find_by(name: 'tactile_text') + doc.xpath("//dcndl:materialType[@rdf:resource]").each do |d| + case d.attributes["resource"].try(:content) + when "http://ndl.go.jp/ndltype/Book" + carrier_type = CarrierType.find_by(name: "print") + content_type = ContentType.find_by(name: "text") + when "http://ndl.go.jp/ndltype/Braille" + content_type = ContentType.find_by(name: "tactile_text") # when 'http://ndl.go.jp/ndltype/ComputerProgram' # content_type = ContentType.find_by(name: 'computer_program') - when 'http://ndl.go.jp/ndltype/ElectronicResource' - carrier_type = CarrierType.find_by(name: 'file') - when 'http://ndl.go.jp/ndltype/Journal' + when "http://ndl.go.jp/ndltype/ElectronicResource" + carrier_type = CarrierType.find_by(name: "file") + when "http://ndl.go.jp/ndltype/Journal" is_serial = true - when 'http://ndl.go.jp/ndltype/Map' - content_type = ContentType.find_by(name: 'cartographic_image') - when 'http://ndl.go.jp/ndltype/Music' - content_type = ContentType.find_by(name: 'performed_music') - when 'http://ndl.go.jp/ndltype/MusicScore' - content_type = ContentType.find_by(name: 'notated_music') - when 'http://ndl.go.jp/ndltype/Painting' - content_type = ContentType.find_by(name: 'still_image') - when 'http://ndl.go.jp/ndltype/Photograph' - content_type = ContentType.find_by(name: 'still_image') - when 'http://ndl.go.jp/ndltype/PicturePostcard' - content_type = ContentType.find_by(name: 'still_image') - when 'http://purl.org/dc/dcmitype/MovingImage' - content_type = ContentType.find_by(name: 'two_dimensional_moving_image') - when 'http://purl.org/dc/dcmitype/Sound' - content_type = ContentType.find_by(name: 'sounds') - when 'http://purl.org/dc/dcmitype/StillImage' - content_type = ContentType.find_by(name: 'still_image') + when "http://ndl.go.jp/ndltype/Map" + content_type = ContentType.find_by(name: "cartographic_image") + when "http://ndl.go.jp/ndltype/Music" + content_type = ContentType.find_by(name: "performed_music") + when "http://ndl.go.jp/ndltype/MusicScore" + content_type = ContentType.find_by(name: "notated_music") + when "http://ndl.go.jp/ndltype/Painting" + content_type = ContentType.find_by(name: "still_image") + when "http://ndl.go.jp/ndltype/Photograph" + content_type = ContentType.find_by(name: "still_image") + when "http://ndl.go.jp/ndltype/PicturePostcard" + content_type = ContentType.find_by(name: "still_image") + when "http://purl.org/dc/dcmitype/MovingImage" + content_type = ContentType.find_by(name: "two_dimensional_moving_image") + when "http://purl.org/dc/dcmitype/Sound" + content_type = ContentType.find_by(name: "sounds") + when "http://purl.org/dc/dcmitype/StillImage" + content_type = ContentType.find_by(name: "still_image") end # NDLサーチのmaterialTypeは複数設定されているが、 @@ -114,15 +114,15 @@ def import_record(doc) break if content_type end - admin_identifier = doc.at('//dcndl:BibAdminResource[@rdf:about]').attributes['about'].value - description = doc.at('//dcterms:abstract').try(:content) - price = doc.at('//dcndl:price').try(:content) - volume_number_string = doc.at('//dcndl:volume/rdf:Description/rdf:value').try(:content) + admin_identifier = doc.at("//dcndl:BibAdminResource[@rdf:about]").attributes["about"].value + description = doc.at("//dcterms:abstract").try(:content) + price = doc.at("//dcndl:price").try(:content) + volume_number_string = doc.at("//dcndl:volume/rdf:Description/rdf:value").try(:content) extent = get_extent(doc) - publication_periodicity = doc.at('//dcndl:publicationPeriodicity').try(:content) - statement_of_responsibility = doc.xpath('//dcndl:BibResource/dc:creator').map(&:content).join('; ') - publication_place = doc.at('//dcterms:publisher/foaf:Agent/dcndl:location').try(:content) - edition_string = doc.at('//dcndl:edition').try(:content) + publication_periodicity = doc.at("//dcndl:publicationPeriodicity").try(:content) + statement_of_responsibility = doc.xpath("//dcndl:BibResource/dc:creator").map(&:content).join("; ") + publication_place = doc.at("//dcterms:publisher/foaf:Agent/dcndl:location").try(:content) + edition_string = doc.at("//dcndl:edition").try(:content) manifestation = Manifestation.find_by(manifestation_identifier: admin_identifier) return manifestation if manifestation @@ -137,7 +137,7 @@ def import_record(doc) title_alternative: title[:alternative], title_alternative_transcription: title[:alternative_transcription], # TODO: NDLサーチに入っている図書以外の資料を調べる - #:carrier_type_id => CarrierType.find_by(name: 'print').id, + # :carrier_type_id => CarrierType.find_by(name: 'print').id, language_id: language_id, pub_date: date, description: description, @@ -190,25 +190,25 @@ def create_additional_attributes(doc, manifestation) creators = get_creators(doc).uniq subjects = get_subjects(doc).uniq classifications = get_classifications(doc).uniq - classification_urls = doc.xpath('//dcterms:subject[@rdf:resource]').map { |subject| subject.attributes['resource'].value } + classification_urls = doc.xpath("//dcterms:subject[@rdf:resource]").map { |subject| subject.attributes["resource"].value } Agent.transaction do creator_agents = Agent.import_agents(creators) content_type_id = begin - ContentType.find_by(name: 'text').id + ContentType.find_by(name: "text").id rescue StandardError 1 end manifestation.creators << creator_agents if defined?(EnjuSubject) - subject_heading_type = SubjectHeadingType.find_or_create_by!(name: 'ndlsh') + subject_heading_type = SubjectHeadingType.find_or_create_by!(name: "ndlsh") subjects.each do |term| subject = Subject.find_by(term: term[:term]) unless subject subject = Subject.new(term) subject.subject_heading_type = subject_heading_type - subject.subject_type = SubjectType.find_or_create_by!(name: 'concept') + subject.subject_type = SubjectType.find_or_create_by!(name: "concept") end # if subject.valid? manifestation.subjects << subject @@ -223,10 +223,10 @@ def create_additional_attributes(doc, manifestation) end next unless ndc_url - ndc_type = ndc_url.path.split('/').reverse[1] - next unless (ndc_type == 'ndc9') || (ndc_type == 'ndc10') + ndc_type = ndc_url.path.split("/").reverse[1] + next unless (ndc_type == "ndc9") || (ndc_type == "ndc10") - ndc = ndc_url.path.split('/').last + ndc = ndc_url.path.split("/").last classification_type = ClassificationType.find_or_create_by!(name: ndc_type) classification = Classification.new(category: ndc) classification.classification_type = classification_type @@ -235,7 +235,7 @@ def create_additional_attributes(doc, manifestation) end ndc8 = doc.xpath('//dc:subject[@rdf:datatype="http://ndl.go.jp/dcndl/terms/NDC8"]').first if ndc8 - classification_type = ClassificationType.find_or_create_by!(name: 'ndc8') + classification_type = ClassificationType.find_or_create_by!(name: "ndc8") classification = Classification.new(category: ndc8.content) classification.classification_type = classification_type manifestation.classifications << classification if classification.valid? @@ -245,7 +245,7 @@ def create_additional_attributes(doc, manifestation) end def search_ndl(query, options = {}) - options = { dpid: 'iss-ndl-opac', item: 'any', idx: 1, per_page: 10, raw: false, mediatype: 'books periodicals video audio scores' }.merge(options) + options = { dpid: "iss-ndl-opac", item: "any", idx: 1, per_page: 10, raw: false, mediatype: "books periodicals video audio scores" }.merge(options) doc = nil results = {} startrecord = options[:idx].to_i @@ -255,8 +255,8 @@ def search_ndl(query, options = {}) if options[:raw] == true URI.parse(url).read else - RSS::Rss::Channel.install_text_element('openSearch:totalResults', 'http://a9.com/-/spec/opensearchrss/1.0/', '?', 'totalResults', :text, 'openSearch:totalResults') - RSS::BaseListener.install_get_text_element 'http://a9.com/-/spec/opensearchrss/1.0/', 'totalResults', 'totalResults=' + RSS::Rss::Channel.install_text_element("openSearch:totalResults", "http://a9.com/-/spec/opensearchrss/1.0/", "?", "totalResults", :text, "openSearch:totalResults") + RSS::BaseListener.install_get_text_element "http://a9.com/-/spec/opensearchrss/1.0/", "totalResults", "totalResults=" RSS::Parser.parse(url, false) end end @@ -278,7 +278,7 @@ def return_xml(isbn: nil, jpno: nil) return end - response = Nokogiri::XML(URI.parse(url).read).at('//xmlns:recordData')&.content + response = Nokogiri::XML(URI.parse(url).read).at("//xmlns:recordData")&.content Nokogiri::XML(response) if response end @@ -287,13 +287,13 @@ def return_xml(isbn: nil, jpno: nil) def get_title(doc) title = { - manifestation: doc.xpath('//dc:title/rdf:Description/rdf:value').collect(&:content).join(' '), - transcription: doc.xpath('//dc:title/rdf:Description/dcndl:transcription').collect(&:content).join(' '), - alternative: doc.at('//dcndl:alternative/rdf:Description/rdf:value').try(:content), - alternative_transcription: doc.at('//dcndl:alternative/rdf:Description/dcndl:transcription').try(:content) + manifestation: doc.xpath("//dc:title/rdf:Description/rdf:value").collect(&:content).join(" "), + transcription: doc.xpath("//dc:title/rdf:Description/dcndl:transcription").collect(&:content).join(" "), + alternative: doc.at("//dcndl:alternative/rdf:Description/rdf:value").try(:content), + alternative_transcription: doc.at("//dcndl:alternative/rdf:Description/dcndl:transcription").try(:content) } - volumeTitle = doc.at('//dcndl:volumeTitle/rdf:Description/rdf:value').try(:content) - volumeTitle_transcription = doc.at('//dcndl:volumeTitle/rdf:Description/dcndl:transcription').try(:content) + volumeTitle = doc.at("//dcndl:volumeTitle/rdf:Description/rdf:value").try(:content) + volumeTitle_transcription = doc.at("//dcndl:volumeTitle/rdf:Description/dcndl:transcription").try(:content) title[:manifestation] << " #{volumeTitle}" if volumeTitle title[:transcription] << " #{volumeTitle_transcription}" if volumeTitle_transcription title @@ -301,11 +301,11 @@ def get_title(doc) def get_creators(doc) creators = [] - doc.xpath('//dcterms:creator/foaf:Agent').each do |creator| + doc.xpath("//dcterms:creator/foaf:Agent").each do |creator| creators << { - full_name: creator.at('./foaf:name').content, - full_name_transcription: creator.at('./dcndl:transcription').try(:content), - ndla_identifier: creator.attributes['about'].try(:content) + full_name: creator.at("./foaf:name").content, + full_name_transcription: creator.at("./dcndl:transcription").try(:content), + ndla_identifier: creator.attributes["about"].try(:content) } end creators @@ -313,10 +313,10 @@ def get_creators(doc) def get_subjects(doc) subjects = [] - doc.xpath('//dcterms:subject/rdf:Description').each do |subject| + doc.xpath("//dcterms:subject/rdf:Description").each do |subject| subjects << { - term: subject.at('./rdf:value').content, - #:url => subject.attribute('about').try(:content) + term: subject.at("./rdf:value").content, + # :url => subject.attribute('about').try(:content) } end subjects @@ -324,9 +324,9 @@ def get_subjects(doc) def get_classifications(doc) classifications = [] - doc.xpath('//dcterms:subject[@rdf:resource]').each do |classification| + doc.xpath("//dcterms:subject[@rdf:resource]").each do |classification| classifications << { - url: classification.attributes['resource'].content + url: classification.attributes["resource"].content } end classifications @@ -340,21 +340,21 @@ def get_language(doc) def get_publishers(doc) publishers = [] - doc.xpath('//dcterms:publisher/foaf:Agent').each do |publisher| + doc.xpath("//dcterms:publisher/foaf:Agent").each do |publisher| publishers << { - full_name: publisher.at('./foaf:name').content, - full_name_transcription: publisher.at('./dcndl:transcription').try(:content), - agent_identifier: publisher.attributes['about'].try(:content) + full_name: publisher.at("./foaf:name").content, + full_name_transcription: publisher.at("./dcndl:transcription").try(:content), + agent_identifier: publisher.attributes["about"].try(:content) } end publishers end def get_extent(doc) - extent = doc.at('//dcterms:extent').try(:content) + extent = doc.at("//dcterms:extent").try(:content) value = { start_page: nil, end_page: nil, height: nil } if extent - extent = extent.split(';') + extent = extent.split(";") page = extent[0].try(:strip) value[:extent] = page if page =~ /\d+p/ @@ -370,13 +370,13 @@ def get_extent(doc) def create_series_statement(doc, manifestation) series = series_title = {} - series[:title] = doc.at('//dcndl:seriesTitle/rdf:Description/rdf:value').try(:content) - series[:title_transcription] = doc.at('//dcndl:seriesTitle/rdf:Description/dcndl:transcription').try(:content) - series[:creator] = doc.at('//dcndl:seriesCreator').try(:content) + series[:title] = doc.at("//dcndl:seriesTitle/rdf:Description/rdf:value").try(:content) + series[:title_transcription] = doc.at("//dcndl:seriesTitle/rdf:Description/dcndl:transcription").try(:content) + series[:creator] = doc.at("//dcndl:seriesCreator").try(:content) if series[:title] - series_title[:title] = series[:title].split(';')[0].strip + series_title[:title] = series[:title].split(";")[0].strip if series[:title_transcription] - series_title[:title_transcription] = series[:title_transcription].split(';')[0].strip + series_title[:title_transcription] = series[:title_transcription].split(";")[0].strip end end @@ -396,7 +396,7 @@ def create_series_statement(doc, manifestation) end def format_query(query) - Addressable::URI.encode(query.to_s.tr(' ', ' ')) + Addressable::URI.encode(query.to_s.tr(" ", " ")) end end diff --git a/app/models/concerns/enju_nii/enju_manifestation.rb b/app/models/concerns/enju_nii/enju_manifestation.rb index 80e46a119f..c3ca621edc 100644 --- a/app/models/concerns/enju_nii/enju_manifestation.rb +++ b/app/models/concerns/enju_nii/enju_manifestation.rb @@ -30,7 +30,7 @@ def import_record_from_cinii_books(doc) # http://ci.nii.ac.jp/info/ja/api/api_outline.html#cib_od # return nil - ncid = doc.at('//cinii:ncid').try(:content) + ncid = doc.at("//cinii:ncid").try(:content) identifier = NcidRecord.find_by(body: ncid) return identifier.manifestation if identifier @@ -42,9 +42,9 @@ def import_record_from_cinii_books(doc) manifestation = Manifestation.new(title) # date of publication - pub_date = doc.at('//dc:date').try(:content) + pub_date = doc.at("//dc:date").try(:content) if pub_date - date = pub_date.split('-') + date = pub_date.split("-") if date[0] && date[1] date = sprintf("%04d-%02d", date[0], date[1]) else @@ -53,9 +53,9 @@ def import_record_from_cinii_books(doc) end manifestation.pub_date = pub_date - manifestation.statement_of_responsibility = doc.at('//dc:creator').try(:content) - manifestation.extent = doc.at('//dcterms:extent').try(:content) - manifestation.dimensions = doc.at('//cinii:size').try(:content) + manifestation.statement_of_responsibility = doc.at("//dc:creator").try(:content) + manifestation.extent = doc.at("//dcterms:extent").try(:content) + manifestation.dimensions = doc.at("//cinii:size").try(:content) language = Language.find_by(iso_639_3: get_cinii_language(doc)) if language @@ -72,8 +72,8 @@ def import_record_from_cinii_books(doc) end end - manifestation.carrier_type = CarrierType.find_by(name: 'volume') - manifestation.manifestation_content_type = ContentType.find_by(name: 'text') + manifestation.carrier_type = CarrierType.find_by(name: "volume") + manifestation.manifestation_content_type = ContentType.find_by(name: "text") if manifestation.valid? Agent.transaction do @@ -87,13 +87,13 @@ def import_record_from_cinii_books(doc) manifestation.creators = creator_patrons if defined?(EnjuSubject) subjects = get_cinii_subjects(doc) - subject_heading_type = SubjectHeadingType.find_or_create_by!(name: 'bsh') + subject_heading_type = SubjectHeadingType.find_or_create_by!(name: "bsh") subjects.each do |term| subject = Subject.find_by(term: term[:term]) unless subject subject = Subject.new(term) subject.subject_heading_type = subject_heading_type - subject_type = SubjectType.find_or_create_by!(name: 'concept') + subject_type = SubjectType.find_or_create_by!(name: "concept") subject.subject_type = subject_type end manifestation.subjects << subject @@ -106,7 +106,7 @@ def import_record_from_cinii_books(doc) end def search_cinii_book(query, options = {}) - options = {p: 1, count: 10, raw: false}.merge(options) + options = { p: 1, count: 10, raw: false }.merge(options) doc = nil results = {} startrecord = options[:idx].to_i @@ -162,24 +162,24 @@ def cinii_normalize_isbn(isbn) end def get_cinii_creator(doc) - doc.xpath("//foaf:maker/foaf:Person").map{|e| + doc.xpath("//foaf:maker/foaf:Person").map { |e| { full_name: e.at("./foaf:name").content&.strip, - full_name_transcription: e.xpath("./foaf:name[@xml:lang]").map{|n| n.content}.join("\n"), + full_name_transcription: e.xpath("./foaf:name[@xml:lang]").map { |n| n.content }.join("\n"), patron_identifier: e.attributes["about"].try(:content) } } end def get_cinii_publisher(doc) - doc.xpath("//dc:publisher").map{|e| {full_name: e.content}} + doc.xpath("//dc:publisher").map { |e| { full_name: e.content } } end def get_cinii_title(doc) { original_title: doc.at("//dc:title[not(@xml:lang)]").children.first.content, - title_transcription: doc.xpath("//dc:title[@xml:lang]", 'dc': 'http://purl.org/dc/elements/1.1/').map{|e| e.try(:content)}.join("\n"), - title_alternative: doc.xpath("//dcterms:alternative").map{|e| e.try(:content)}.join("\n") + title_transcription: doc.xpath("//dc:title[@xml:lang]", 'dc': "http://purl.org/dc/elements/1.1/").map { |e| e.try(:content) }.join("\n"), + title_alternative: doc.xpath("//dcterms:alternative").map { |e| e.try(:content) }.join("\n") } end @@ -194,7 +194,7 @@ def get_cinii_language(doc) def get_cinii_subjects(doc) subjects = [] - doc.xpath('//foaf:topic').each do |s| + doc.xpath("//foaf:topic").each do |s| subjects << { term: s["dc:title"] } end subjects diff --git a/app/models/concerns/enju_oai/dcndl.rb b/app/models/concerns/enju_oai/dcndl.rb index f71bb958e0..ae0d20cd78 100644 --- a/app/models/concerns/enju_oai/dcndl.rb +++ b/app/models/concerns/enju_oai/dcndl.rb @@ -2,13 +2,13 @@ module EnjuOai class Dcndl < OAI::Provider::Metadata::Format def initialize - @prefix = 'dcndl' + @prefix = "dcndl" @schema = nil - @namespace = 'http://ndl.go.jp/dcndl/terms/' - @element_namespace = 'dc' + @namespace = "http://ndl.go.jp/dcndl/terms/" + @element_namespace = "dc" @fields = [ :title, :creator, :subject, :description, :publisher, :contributor, :date, :type, :format, :identifier, - :source, :language, :relation, :coverage, :rights] + :source, :language, :relation, :coverage, :rights ] end end end diff --git a/app/models/concerns/enju_oai/jpcoar.rb b/app/models/concerns/enju_oai/jpcoar.rb index 495befddca..d5daad61dd 100644 --- a/app/models/concerns/enju_oai/jpcoar.rb +++ b/app/models/concerns/enju_oai/jpcoar.rb @@ -2,23 +2,23 @@ module EnjuOai class Jpcoar < OAI::Provider::Metadata::Format def initialize - @prefix = 'jpcoar' - @schema = 'https://github.com/JPCOAR/schema/blob/master/1.0/jpcoar_scm.xsd' - @namespace = 'https://github.com/JPCOAR/schema/blob/master/1.0/' - @element_namespace = 'dc' + @prefix = "jpcoar" + @schema = "https://github.com/JPCOAR/schema/blob/master/1.0/jpcoar_scm.xsd" + @namespace = "https://github.com/JPCOAR/schema/blob/master/1.0/" + @element_namespace = "dc" @fields = [ :title, :creator, :subject, :description, :publisher, :contributor, :date, :type, :format, :identifier, - :source, :language, :relation, :coverage, :rights] + :source, :language, :relation, :coverage, :rights ] end def header_specification { - 'xmlns:jpcoar' => "https://github.com/JPCOAR/schema/blob/master/1.0/", - 'xmlns:dc' => "http://purl.org/dc/elements/1.1/", - 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", - 'xsi:schemaLocation' => - %{https://github.com/JPCOAR/schema/blob/master/1.0/ - jpcoar_scm.xsd}.gsub(/\s+/, ' ') + "xmlns:jpcoar" => "https://github.com/JPCOAR/schema/blob/master/1.0/", + "xmlns:dc" => "http://purl.org/dc/elements/1.1/", + "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", + "xsi:schemaLocation" => + %(https://github.com/JPCOAR/schema/blob/master/1.0/ + jpcoar_scm.xsd).gsub(/\s+/, " ") } end diff --git a/app/models/concerns/enju_oai/oai_model.rb b/app/models/concerns/enju_oai/oai_model.rb index fbc2459156..f1182f2457 100644 --- a/app/models/concerns/enju_oai/oai_model.rb +++ b/app/models/concerns/enju_oai/oai_model.rb @@ -7,20 +7,20 @@ module OaiModel def to_oai_dc xml = Builder::XmlMarkup.new xml.tag!("oai_dc:dc", - 'xmlns:oai_dc' => "http://www.openarchives.org/OAI/2.0/oai_dc/", - 'xmlns:dc' => "http://purl.org/dc/elements/1.1/", - 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", - 'xsi:schemaLocation' => - %{http://www.openarchives.org/OAI/2.0/oai_dc/ - http://www.openarchives.org/OAI/2.0/oai_dc.xsd}) do - xml.tag! 'dc:title', original_title + "xmlns:oai_dc" => "http://www.openarchives.org/OAI/2.0/oai_dc/", + "xmlns:dc" => "http://purl.org/dc/elements/1.1/", + "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", + "xsi:schemaLocation" => + %(http://www.openarchives.org/OAI/2.0/oai_dc/ + http://www.openarchives.org/OAI/2.0/oai_dc.xsd)) do + xml.tag! "dc:title", original_title creators.readable_by(nil).each do |creator| - xml.tag! 'dc:creator', creator.full_name + xml.tag! "dc:creator", creator.full_name end subjects.each do |subject| - xml.tag! 'dc:subject', subject.term + xml.tag! "dc:subject", subject.term end - xml.tag! 'dc:description', description + xml.tag! "dc:description", description end xml.target! @@ -28,7 +28,7 @@ def to_oai_dc def to_jpcoar xml = Builder::XmlMarkup.new - xml.tag!('jpcoar:jpcoar', "xsi:schemaLocation" => "https://github.com/JPCOAR/schema/blob/master/1.0/jpcoar_scm.xsd", + xml.tag!("jpcoar:jpcoar", "xsi:schemaLocation" => "https://github.com/JPCOAR/schema/blob/master/1.0/jpcoar_scm.xsd", "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", "xmlns:rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "xmlns:rioxxterms" => "http://www.rioxx.net/schema/v2.0/rioxxterms/", @@ -37,21 +37,21 @@ def to_jpcoar "xmlns:dcndl" => "http://ndl.go.jp/dcndl/terms/", "xmlns:dc" => "http://purl.org/dc/elements/1.1/", "xmlns:jpcoar" => "https://github.com/JPCOAR/schema/blob/master/1.0/") do - xml.tag! 'dc:title', original_title - xml.tag! 'dc:language', language.iso_639_2 - xml.tag! 'jpcoar:creators' do + xml.tag! "dc:title", original_title + xml.tag! "dc:language", language.iso_639_2 + xml.tag! "jpcoar:creators" do creators.readable_by(nil).each do |creator| - xml.tag! 'jpcoar:creatorName', creator.full_name + xml.tag! "jpcoar:creatorName", creator.full_name end end subjects.each do |subject| - xml.tag! 'jpcoar:subject', subject.term + xml.tag! "jpcoar:subject", subject.term end if attachment.attached? - xml.tag! 'jpcoar:file' do - xml.tag! 'jpcoar:URI', Rails.application.routes.url_helpers.rails_storage_proxy_url(fileset.attachment, host: ENV['ENJU_LEAF_BASE_URL']) + xml.tag! "jpcoar:file" do + xml.tag! "jpcoar:URI", Rails.application.routes.url_helpers.rails_storage_proxy_url(fileset.attachment, host: ENV["ENJU_LEAF_BASE_URL"]) end end end @@ -69,23 +69,23 @@ def to_dcndl "xmlns:rdfs" => "http://www.w3.org/2000/01/rdf-schema#", "xmlns:owl" => "http://www.w3.org/2002/07/owl#", "xmlns:foaf" => "http://xmlns.com/foaf/0.1/" do - get_record_url = URI.join(ENV['ENJU_LEAF_BASE_URL'], "/oai?verb=GetRecord&metadataPrefix=dcndl&identifier=#{oai_identifier}") + get_record_url = URI.join(ENV["ENJU_LEAF_BASE_URL"], "/oai?verb=GetRecord&metadataPrefix=dcndl&identifier=#{oai_identifier}") xml.tag! "dcndl:BibAdminResource", "rdf:about" => get_record_url do xml.tag! "dcndl:record", "rdf:resource" => get_record_url + "#material" - xml.tag! "dcndl:bibRecordCategory", ENV['DCNDL_BIBRECORDCATEGORY'] + xml.tag! "dcndl:bibRecordCategory", ENV["DCNDL_BIBRECORDCATEGORY"] end xml.tag! "dcndl:BibResource", "rdf:about" => get_record_url + "#material" do - xml.tag! "rdfs:seeAlso", "rdf:resource" => URI.join(ENV['ENJU_LEAF_BASE_URL'], "/manifestations/#{id}") + xml.tag! "rdfs:seeAlso", "rdf:resource" => URI.join(ENV["ENJU_LEAF_BASE_URL"], "/manifestations/#{id}") identifiers.each do |identifier| case identifier.identifier_type.try(:name) - when 'isbn' + when "isbn" # xml.tag! "rdfs:seeAlso", "rdf:resource" => "http://iss.ndl.go.jp/isbn/#{identifier.body}" xml.tag! "dcterms:identifier", identifier.body, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/ISBN" - when 'issn' + when "issn" xml.tag! "dcterms:identifier", identifier.body, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/ISSN" - when 'doi' + when "doi" xml.tag! "dcterms:identifier", identifier.body, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/DOI" - when 'ncid' + when "ncid" xml.tag! "dcterms:identifier", identifier.body, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/NIIBibID" end @@ -187,26 +187,26 @@ def to_dcndl end classifications.each do |classification| case classification.classification_type.name - when 'ndlc' + when "ndlc" xml.tag! "dcterms:subject", "rdf:resource" => "http://id.ndl.go.jp/class/ndlc/" + classification.category - when 'ndc9' + when "ndc9" xml.tag! "dcterms:subject", "rdf:resource" => "http://id.ndl.go.jp/class/ndc9/" + classification.category - when 'ddc' + when "ddc" xml.tag! "dcterms:subject", "rdf:resource" => "http://dewey.info/class/" + classification.category - when 'ndc8' + when "ndc8" xml.tag! "dc:subject", classification.category, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/NDC8" - when 'ndc' + when "ndc" xml.tag! "dc:subject", classification.category, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/NDC" - when 'lcc' + when "lcc" xml.tag! "dc:subject", classification.category, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/LCC" - when 'udc' + when "udc" xml.tag! "dc:subject", classification.category, "rdf:datatype" => "http://ndl.go.jp/dcndl/terms/UDC" end end xml.tag! "dcterms:language", language.iso_639_2, "rdf:datatype" => "http://purl.org/dc/terms/ISO639-2" xml.tag! "dcndl:price", price if price? if extent? || dimensions? - xml.tag! "dcterms:extent", [extent, dimensions].compact.join(" ; ") + xml.tag! "dcterms:extent", [ extent, dimensions ].compact.join(" ; ") end material_type = nil case carrier_type.name @@ -263,7 +263,7 @@ def to_dcndl end def self.repository_url - URI.join(ENV['ENJU_LEAF_BASE_URL'], '/oai') + URI.join(ENV["ENJU_LEAF_BASE_URL"], "/oai") end def self.record_prefix @@ -271,7 +271,7 @@ def self.record_prefix end def oai_identifier - [EnjuOai::OaiModel.record_prefix, id].join(':') + [ EnjuOai::OaiModel.record_prefix, id ].join(":") end end end diff --git a/app/models/concerns/enju_seed/enju_user.rb b/app/models/concerns/enju_seed/enju_user.rb index 7cb042a043..6e4550967b 100644 --- a/app/models/concerns/enju_seed/enju_user.rb +++ b/app/models/concerns/enju_seed/enju_user.rb @@ -3,8 +3,8 @@ module EnjuUser extend ActiveSupport::Concern included do - scope :administrators, -> { joins(:role).where('roles.name = ?', 'Administrator') } - scope :librarians, -> { joins(:role).where('roles.name = ? OR roles.name = ?', 'Administrator', 'Librarian') } + scope :administrators, -> { joins(:role).where("roles.name = ?", "Administrator") } + scope :librarians, -> { joins(:role).where("roles.name = ? OR roles.name = ?", "Administrator", "Librarian") } scope :suspended, -> { where.not(locked_at: nil) } has_one :profile, dependent: :nullify if defined?(EnjuBiblio) @@ -40,7 +40,7 @@ module EnjuUser attr_accessor :password_not_verified, :update_own_account, :auto_generated_password, - :locked, :current_password #, :agent_id + :locked, :current_password # , :agent_id paginates_per 10 @@ -57,8 +57,8 @@ def self.lock_expired_users # ユーザの情報をエクスポートします。 # @param [Hash] options - def self.export(options = {format: :text}) - header = %w( + def self.export(options = { format: :text }) + header = %w[ username full_name full_name_transcription @@ -75,15 +75,15 @@ def self.export(options = {format: :text}) expired_at keyword_list note - ) - header += %w( + ] + header += %w[ checkout_icalendar_token save_checkout_history - ) if defined? EnjuCirculation + ] if defined? EnjuCirculation header << "save_search_history" if defined? EnjuSearchLog header << "share_bookmarks" if defined? EnjuBookmark lines = [] - User.find_each.map{|u| + User.find_each.map { |u| line = [] line << u.username line << u.try(:profile).try(:full_name) @@ -114,7 +114,7 @@ def self.export(options = {format: :text}) lines << line } if options[:format] == :text - lines.map{|line| line.to_csv(col_sep: "\t")}.unshift(header.to_csv(col_sep: "\t")).join + lines.map { |line| line.to_csv(col_sep: "\t") }.unshift(header.to_csv(col_sep: "\t")).join else lines end @@ -137,10 +137,10 @@ def has_role?(role_in_question) return true if role.name == role_in_question case role.name - when 'Administrator' + when "Administrator" return true - when 'Librarian' - return true if role_in_question == 'User' + when "Librarian" + return true if role_in_question == "User" else false end @@ -148,9 +148,9 @@ def has_role?(role_in_question) # ユーザに使用不可の設定を反映させます。 def set_lock_information - if locked == '1' && active_for_authentication? + if locked == "1" && active_for_authentication? lock_access! - elsif locked == '0' && !active_for_authentication? + elsif locked == "0" && !active_for_authentication? unlock_access! end end @@ -165,7 +165,7 @@ def set_confirmation # ユーザが有効期限切れかどうかをチェックし、期限切れであれば使用不可に設定します。 # @return [Object] def check_expiration - return if has_role?('Administrator') + return if has_role?("Administrator") if expired_at if expired_at.beginning_of_day < Time.zone.now.beginning_of_day @@ -177,9 +177,9 @@ def check_expiration # ユーザの削除前に、管理者ユーザが不在にならないかどうかをチェックします。 # @return [Object] def check_role_before_destroy - if has_role?('Administrator') - if Role.find_by(name: 'Administrator').users.count == 1 - raise username + 'This is the last administrator in this system.' + if has_role?("Administrator") + if Role.find_by(name: "Administrator").users.count == 1 + raise username + "This is the last administrator in this system." end end end @@ -203,7 +203,7 @@ def expired? # ユーザが管理者かどうかをチェックします。 # @return [Boolean] def is_admin? - return true if has_role?('Administrator') + return true if has_role?("Administrator") false end @@ -211,8 +211,8 @@ def is_admin? # ユーザがシステム上の最後のLibrarian権限ユーザかどうかをチェックします。 # @return [Boolean] def last_librarian? - if has_role?('Librarian') - role = Role.find_by(name: 'Librarian') + if has_role?("Librarian") + role = Role.find_by(name: "Librarian") return true if role.users.count == 1 false @@ -232,25 +232,25 @@ def deletable_by?(current_user) if defined?(EnjuCirculation) # 未返却の資料のあるユーザを削除しようとした if checkouts.count.positive? - errors.add(:base, I18n.t('user.this_user_has_checked_out_item')) + errors.add(:base, I18n.t("user.this_user_has_checked_out_item")) end end - if has_role?('Librarian') + if has_role?("Librarian") # 管理者以外のユーザが図書館員を削除しようとした。図書館員の削除は管理者しかできない - unless current_user.has_role?('Administrator') - errors.add(:base, I18n.t('user.only_administrator_can_destroy')) + unless current_user.has_role?("Administrator") + errors.add(:base, I18n.t("user.only_administrator_can_destroy")) end # 最後の図書館員を削除しようとした if last_librarian? - errors.add(:base, I18n.t('user.last_librarian')) + errors.add(:base, I18n.t("user.last_librarian")) end end # 最後の管理者を削除しようとした - if has_role?('Administrator') - if Role.find_by(name: 'Administrator').users.count == 1 - errors.add(:base, I18n.t('user.last_administrator')) + if has_role?("Administrator") + if Role.find_by(name: "Administrator").users.count == 1 + errors.add(:base, I18n.t("user.last_administrator")) end end diff --git a/app/models/concerns/enju_subject/enju_manifestation.rb b/app/models/concerns/enju_subject/enju_manifestation.rb index b6969d574c..2dac9af7af 100644 --- a/app/models/concerns/enju_subject/enju_manifestation.rb +++ b/app/models/concerns/enju_subject/enju_manifestation.rb @@ -16,13 +16,13 @@ module EnjuManifestation searchable do text :subject do - subjects.map{|s| [s.term, s.term_transcription]}.flatten.compact + subjects.map { |s| [ s.term, s.term_transcription ] }.flatten.compact end string :subject, multiple: true do - subjects.map{|s| [s.term, s.term_transcription]}.flatten.compact + subjects.map { |s| [ s.term, s.term_transcription ] }.flatten.compact end string :classification, multiple: true do - classifications.map{|c| "#{c.classification_type.name}_#{c.category}"} + classifications.map { |c| "#{c.classification_type.name}_#{c.category}" } end integer :subject_ids, multiple: true end diff --git a/app/models/concerns/import_file.rb b/app/models/concerns/import_file.rb index 2aaf86ce21..83864a58c3 100644 --- a/app/models/concerns/import_file.rb +++ b/app/models/concerns/import_file.rb @@ -10,11 +10,11 @@ def self.expire def import_start case edit_mode - when 'create' + when "create" import - when 'update' + when "update" modify - when 'destroy' + when "destroy" remove else import @@ -27,14 +27,14 @@ def convert_encoding(line) if defined?(CharlockHolmes::EncodingDetector) begin case user_encoding - when 'auto_detect' + when "auto_detect" encoding = CharlockHolmes::EncodingDetector.detect(line)[:encoding] when nil encoding = CharlockHolmes::EncodingDetector.detect(line)[:encoding] else encoding = user_encoding end - line.encode('UTF-8', encoding, universal_newline: true) + line.encode("UTF-8", encoding, universal_newline: true) rescue StandardError nkf_encode(line) end @@ -58,16 +58,16 @@ def send_message(mailer) def nkf_encode(line) case user_encoding - when 'auto_detect' - output_encoding = '-w' - when 'UTF-8' - output_encoding = '' - when 'Shift_JIS' - output_encoding = '-Sw' - when 'EUC-JP' - output_encoding = '-Ew' + when "auto_detect" + output_encoding = "-w" + when "UTF-8" + output_encoding = "" + when "Shift_JIS" + output_encoding = "-Sw" + when "EUC-JP" + output_encoding = "-Ew" else - output_encoding = '-w' + output_encoding = "-w" end NKF.nkf("#{output_encoding} -Lu", line) end diff --git a/app/models/concerns/master_model.rb b/app/models/concerns/master_model.rb index 2b2236b228..48d8ee24c8 100644 --- a/app/models/concerns/master_model.rb +++ b/app/models/concerns/master_model.rb @@ -24,7 +24,7 @@ def set_display_name private def valid_name? unless name =~ /\A[a-z][0-9a-z_]*[0-9a-z]\z/ - errors.add(:name, I18n.t('page.only_lowercase_letters_and_numbers_are_allowed')) + errors.add(:name, I18n.t("page.only_lowercase_letters_and_numbers_are_allowed")) end end @@ -32,7 +32,7 @@ def valid_yaml? begin YAML.load(display_name) rescue Psych::SyntaxError - errors.add(:display_name, I18n.t('page.cannot_parse_yaml_header')) + errors.add(:display_name, I18n.t("page.cannot_parse_yaml_header")) end end end diff --git a/app/models/country.rb b/app/models/country.rb index c3234f24d1..31be2b5ba5 100644 --- a/app/models/country.rb +++ b/app/models/country.rb @@ -1,6 +1,6 @@ class Country < ApplicationRecord include MasterModel - default_scope { order('countries.position') } + default_scope { order("countries.position") } has_many :agents, dependent: :destroy has_many :libraries, dependent: :destroy has_one :library_group @@ -18,11 +18,11 @@ class Country < ApplicationRecord after_save :clear_all_cache def self.all_cache - Rails.cache.fetch('country_all'){Country.all.to_a} + Rails.cache.fetch("country_all") { Country.all.to_a } end def clear_all_cache - Rails.cache.delete('country_all') + Rails.cache.delete("country_all") end private diff --git a/app/models/create.rb b/app/models/create.rb index b7509978e4..42514baa54 100644 --- a/app/models/create.rb +++ b/app/models/create.rb @@ -1,6 +1,6 @@ class Create < ApplicationRecord belongs_to :agent - belongs_to :work, class_name: 'Manifestation', touch: true + belongs_to :work, class_name: "Manifestation", touch: true belongs_to :create_type, optional: true validates :work_id, uniqueness: { scope: :agent_id } diff --git a/app/models/create_type.rb b/app/models/create_type.rb index ba5383374f..dfaaa1a759 100644 --- a/app/models/create_type.rb +++ b/app/models/create_type.rb @@ -1,6 +1,6 @@ class CreateType < ApplicationRecord include MasterModel - default_scope { order('create_types.position') } + default_scope { order("create_types.position") } end # == Schema Information diff --git a/app/models/event.rb b/app/models/event.rb index 15fc7c54b1..f7fe77d107 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -1,15 +1,15 @@ class Event < ApplicationRecord - scope :closing_days, -> { includes(:event_category).where('event_categories.name' => 'closed') } - scope :on, lambda {|datetime| - where('start_at >= ? AND start_at < ?', datetime.beginning_of_day, datetime.tomorrow.beginning_of_day + 1) + scope :closing_days, -> { includes(:event_category).where("event_categories.name" => "closed") } + scope :on, lambda { |datetime| + where("start_at >= ? AND start_at < ?", datetime.beginning_of_day, datetime.tomorrow.beginning_of_day + 1) } - scope :past, lambda {|datetime| - where('end_at <= ?', Time.zone.parse(datetime).beginning_of_day) + scope :past, lambda { |datetime| + where("end_at <= ?", Time.zone.parse(datetime).beginning_of_day) } - scope :upcoming, lambda {|datetime| - where('start_at >= ?', Time.zone.parse(datetime).beginning_of_day) + scope :upcoming, lambda { |datetime| + where("start_at >= ?", Time.zone.parse(datetime).beginning_of_day) } - scope :at, lambda {|library| + scope :at, lambda { |library| where(library_id: library.id) } @@ -65,13 +65,13 @@ def set_display_name # CSVのヘッダ # @param [String] role 権限 - def self.csv_header(role: 'Guest') + def self.csv_header(role: "Guest") Event.new.to_hash(role: role).keys end # CSV出力用のハッシュ # @param [String] role 権限 - def to_hash(role: 'Guest') + def to_hash(role: "Guest") record = { name: name, display_name: display_name, @@ -91,8 +91,8 @@ def to_hash(role: 'Guest') # TSVでのエクスポート # @param [String] role 権限 # @param [String] col_sep 区切り文字 - def self.export(role: 'Guest', col_sep: "\t") - Tempfile.create('event_export') do |f| + def self.export(role: "Guest", col_sep: "\t") + Tempfile.create("event_export") do |f| f.write Event.csv_header(role: role).to_csv(col_sep: col_sep) Event.find_each do |event| f.write event.to_hash(role: role).values.to_csv(col_sep: col_sep) diff --git a/app/models/event_category.rb b/app/models/event_category.rb index af733b4513..a8f8a73064 100644 --- a/app/models/event_category.rb +++ b/app/models/event_category.rb @@ -2,7 +2,7 @@ class EventCategory < ApplicationRecord # include MasterModel validates :name, presence: true acts_as_list - default_scope { order('position') } + default_scope { order("position") } has_many :events, dependent: :restrict_with_exception paginates_per 10 diff --git a/app/models/event_export_file.rb b/app/models/event_export_file.rb index bf766ae6c8..67d1a86fd6 100644 --- a/app/models/event_export_file.rb +++ b/app/models/event_export_file.rb @@ -22,7 +22,7 @@ def export! EventExportFile.transaction do transition_to!(:started) role_name = user.try(:role).try(:name) - attachment.attach(io: StringIO.new(tsv), filename: 'event_export.txt') + attachment.attach(io: StringIO.new(tsv), filename: "event_export.txt") save! transition_to!(:completed) end diff --git a/app/models/event_export_file_state_machine.rb b/app/models/event_export_file_state_machine.rb index 6d75eb3602..a83a0b3033 100644 --- a/app/models/event_export_file_state_machine.rb +++ b/app/models/event_export_file_state_machine.rb @@ -7,7 +7,7 @@ class EventExportFileStateMachine state :failed transition from: :pending, to: :started - transition from: :started, to: [:completed, :failed] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |event_export_file| event_export_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/event_export_file_transition.rb b/app/models/event_export_file_transition.rb index d6c2c752ab..19f7a6f356 100644 --- a/app/models/event_export_file_transition.rb +++ b/app/models/event_export_file_transition.rb @@ -1,7 +1,4 @@ class EventExportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :event_export_file, inverse_of: :event_export_file_transitions end @@ -11,7 +8,7 @@ class EventExportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # event_export_file_id :bigint # created_at :datetime not null diff --git a/app/models/event_import_file.rb b/app/models/event_import_file.rb index 5b1837c9e2..e02b13f833 100644 --- a/app/models/event_import_file.rb +++ b/app/models/event_import_file.rb @@ -4,13 +4,13 @@ class EventImportFile < ApplicationRecord initial_state: EventImportFileStateMachine.initial_state ] include ImportFile - scope :not_imported, -> {in_state(:pending)} - scope :stucked, -> {in_state(:pending).where('event_import_files.created_at < ?', 1.hour.ago)} + scope :not_imported, -> { in_state(:pending) } + scope :stucked, -> { in_state(:pending).where("event_import_files.created_at < ?", 1.hour.ago) } has_one_attached :attachment belongs_to :user - belongs_to :default_library, class_name: 'Library', optional: true - belongs_to :default_event_category, class_name: 'EventCategory', optional: true + belongs_to :default_library, class_name: "Library", optional: true + belongs_to :default_event_category, class_name: "EventCategory", optional: true has_many :event_import_results, dependent: :destroy has_many :event_import_file_transitions, autosave: false, dependent: :destroy @@ -33,26 +33,26 @@ def import rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? event_import_result = EventImportResult.new(event_import_file_id: id, body: row.fields.join("\t")) event = Event.new - event.name = row['name'].to_s.strip - event.display_name = row['display_name'] - event.note = row['note'] - event.start_at = Time.zone.parse(row['start_at']) if row['start_at'].present? - event.end_at = Time.zone.parse(row['end_at']) if row['end_at'].present? - category = row['event_category'].to_s.strip - if %w(t true TRUE).include?(row['all_day'].to_s.strip) + event.name = row["name"].to_s.strip + event.display_name = row["display_name"] + event.note = row["note"] + event.start_at = Time.zone.parse(row["start_at"]) if row["start_at"].present? + event.end_at = Time.zone.parse(row["end_at"]) if row["end_at"].present? + category = row["event_category"].to_s.strip + if %w[t true TRUE].include?(row["all_day"].to_s.strip) event.all_day = true else event.all_day = false end - library = Library.find_by(name: row['library']) + library = Library.find_by(name: row["library"]) library = default_library || Library.web if library.blank? event.library = library - event_category = EventCategory.find_by(name: row['event_category']) + event_category = EventCategory.find_by(name: row["event_category"]) event_category = default_event_category if event_category.blank? event.event_category = event_category @@ -87,18 +87,18 @@ def modify rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? - event = Event.find(row['id'].to_s.strip) - event_category = EventCategory.find_by(name: row['event_category'].to_s.strip) + event = Event.find(row["id"].to_s.strip) + event_category = EventCategory.find_by(name: row["event_category"].to_s.strip) event.event_category = event_category if event_category - library = Library.find_by(name: row['library'].to_s.strip) + library = Library.find_by(name: row["library"].to_s.strip) event.library = library if library - event.name = row['name'] if row['name'].to_s.strip.present? - event.start_at = Time.zone.parse(row['start_at']) if row['start_at'].present? - event.end_at = Time.zone.parse(row['end_at']) if row['end_at'].present? - event.note = row['note'] if row['note'].to_s.strip.present? - if %w(t true TRUE).include?(row['all_day'].to_s.strip) + event.name = row["name"] if row["name"].to_s.strip.present? + event.start_at = Time.zone.parse(row["start_at"]) if row["start_at"].present? + event.end_at = Time.zone.parse(row["end_at"]) if row["end_at"].present? + event.note = row["note"] if row["note"].to_s.strip.present? + if %w[t true TRUE].include?(row["all_day"].to_s.strip) event.all_day = true else event.all_day = false @@ -125,9 +125,9 @@ def remove rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? - event = Event.find(row['id'].to_s.strip) + event = Event.find(row["id"].to_s.strip) event.picture_files.destroy_all # workaround event.reload event.destroy @@ -160,7 +160,7 @@ def open_import_file(tempfile) header = file.first ignored_columns = header - header_columns unless ignored_columns.empty? - self.error_message = I18n.t('import.following_column_were_ignored', column: ignored_columns.join(', ')) + self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", ")) save! end rows = CSV.open(tempfile, headers: header, col_sep: "\t") @@ -173,10 +173,10 @@ def open_import_file(tempfile) end def check_field(field) - if [field['name']].reject{|f| f.to_s.strip == ""}.empty? + if [ field["name"] ].reject { |f| f.to_s.strip == "" }.empty? raise "You should specify a name in the first line" end - if [field['start_at'], field['end_at']].reject{|f| f.to_s.strip == ""}.empty? + if [ field["start_at"], field["end_at"] ].reject { |f| f.to_s.strip == "" }.empty? raise "You should specify dates in the first line" end end diff --git a/app/models/event_import_file_state_machine.rb b/app/models/event_import_file_state_machine.rb index 86851a29e3..e5441735a3 100644 --- a/app/models/event_import_file_state_machine.rb +++ b/app/models/event_import_file_state_machine.rb @@ -7,7 +7,7 @@ class EventImportFileStateMachine state :failed transition from: :pending, to: :started - transition from: :started, to: [:completed, :failed] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |event_import_file| event_import_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/event_import_file_transition.rb b/app/models/event_import_file_transition.rb index 42828033ec..26a38b48e4 100644 --- a/app/models/event_import_file_transition.rb +++ b/app/models/event_import_file_transition.rb @@ -1,7 +1,4 @@ class EventImportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :event_import_file, inverse_of: :event_import_file_transitions end @@ -11,7 +8,7 @@ class EventImportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # event_import_file_id :bigint # created_at :datetime not null diff --git a/app/models/event_import_result.rb b/app/models/event_import_result.rb index 3c4466c5f9..085f2e9915 100644 --- a/app/models/event_import_result.rb +++ b/app/models/event_import_result.rb @@ -1,14 +1,14 @@ class EventImportResult < ApplicationRecord - scope :file_id, proc{|file_id| where(event_import_file_id: file_id)} + scope :file_id, proc { |file_id| where(event_import_file_id: file_id) } scope :failed, -> { where(event_id: nil) } belongs_to :event_import_file belongs_to :event, optional: true def self.header - %w( + %w[ id name display_name library event_category start_at end_at all_day note dummy - ) + ] end end diff --git a/app/models/form_of_work.rb b/app/models/form_of_work.rb index 598a5f1fec..e08bbc29a1 100644 --- a/app/models/form_of_work.rb +++ b/app/models/form_of_work.rb @@ -1,6 +1,6 @@ class FormOfWork < ApplicationRecord include MasterModel - has_many :works, class_name: 'Manifestation' #, dependent: :restrict_with_exception + has_many :works, class_name: "Manifestation" # , dependent: :restrict_with_exception end # == Schema Information diff --git a/app/models/identifier.rb b/app/models/identifier.rb index 198ffc2faa..8563905d67 100644 --- a/app/models/identifier.rb +++ b/app/models/identifier.rb @@ -3,7 +3,7 @@ class Identifier < ApplicationRecord belongs_to :manifestation, touch: true, optional: true validates :body, presence: true - validates :body, uniqueness: { scope: [:identifier_type_id, :manifestation_id] } + validates :body, uniqueness: { scope: [ :identifier_type_id, :manifestation_id ] } validate :check_identifier before_validation :normalize before_save :convert_isbn @@ -20,22 +20,22 @@ class Identifier < ApplicationRecord def check_identifier case identifier_type.try(:name) - when 'isbn' + when "isbn" unless StdNum::ISBN.valid?(body) errors.add(:body) end - when 'issn' + when "issn" unless StdNum::ISSN.valid?(body) errors.add(:body) end - when 'lccn' + when "lccn" unless StdNum::LCCN.valid?(body) errors.add(:body) end - when 'doi' + when "doi" if URI.parse(body).scheme errors.add(:body) end @@ -43,7 +43,7 @@ def check_identifier end def convert_isbn - if identifier_type.name == 'isbn' + if identifier_type.name == "isbn" lisbn = Lisbn.new(body) if lisbn.isbn if lisbn.isbn.length == 10 @@ -54,19 +54,19 @@ def convert_isbn end def hyphenated_isbn - if identifier_type.name == 'isbn' + if identifier_type.name == "isbn" lisbn = Lisbn.new(body) - lisbn.parts.join('-') + lisbn.parts.join("-") end end def normalize case identifier_type.try(:name) - when 'isbn' + when "isbn" self.body = StdNum::ISBN.normalize(body) - when 'issn' + when "issn" self.body = StdNum::ISSN.normalize(body) - when 'lccn' + when "lccn" self.body = StdNum::LCCN.normalize(body) end end diff --git a/app/models/identity.rb b/app/models/identity.rb index 46cf34db01..56c1cfaf94 100644 --- a/app/models/identity.rb +++ b/app/models/identity.rb @@ -1,6 +1,6 @@ class Identity < ApplicationRecord belongs_to :profile - validates :name, presence: true, uniqueness: {scope: :provider} + validates :name, presence: true, uniqueness: { scope: :provider } validates :provider, presence: true def self.find_for_oauth(auth) diff --git a/app/models/import_request.rb b/app/models/import_request.rb index cbbbbd6669..1834c3f653 100644 --- a/app/models/import_request.rb +++ b/app/models/import_request.rb @@ -3,13 +3,13 @@ class ImportRequest < ApplicationRecord transition_class: ImportRequestTransition, initial_state: ImportRequestStateMachine.initial_state ] - default_scope { order('import_requests.id DESC') } + default_scope { order("import_requests.id DESC") } belongs_to :manifestation, optional: true belongs_to :user validates :isbn, presence: true validate :check_isbn - #validate :check_imported, on: :create - #validates_uniqueness_of :isbn, if: Proc.new{|request| ImportRequest.where("created_at > ?", 1.day.ago).collect(&:isbn).include?(request.isbn)} + # validate :check_imported, on: :create + # validates_uniqueness_of :isbn, if: Proc.new{|request| ImportRequest.where("created_at > ?", 1.day.ago).collect(&:isbn).include?(request.isbn)} has_many :import_request_transitions, autosave: false, dependent: :destroy @@ -30,13 +30,13 @@ def check_imported if isbn.present? lisbn = Lisbn.new(isbn) if IsbnRecord.find_by(body: lisbn.isbn13)&.manifestations - errors.add(:isbn, I18n.t('import_request.isbn_taken')) + errors.add(:isbn, I18n.t("import_request.isbn_taken")) end end end def import! - exceptions = [ActiveRecord::RecordInvalid, NameError, URI::InvalidURIError] + exceptions = [ ActiveRecord::RecordInvalid, NameError, URI::InvalidURIError ] not_found_exceptions = [] not_found_exceptions << EnjuNdl::RecordNotFound if defined? EnjuNdl not_found_exceptions << EnjuNii::RecordNotFound if defined? EnjuNii diff --git a/app/models/import_request_state_machine.rb b/app/models/import_request_state_machine.rb index f3b0c8274c..79d335c768 100644 --- a/app/models/import_request_state_machine.rb +++ b/app/models/import_request_state_machine.rb @@ -5,5 +5,5 @@ class ImportRequestStateMachine state :completed state :failed - transition from: :pending, to: [:completed, :failed] + transition from: :pending, to: [ :completed, :failed ] end diff --git a/app/models/import_request_transition.rb b/app/models/import_request_transition.rb index 266862a3bf..a4f84acbbb 100644 --- a/app/models/import_request_transition.rb +++ b/app/models/import_request_transition.rb @@ -1,7 +1,4 @@ class ImportRequestTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :import_request, inverse_of: :import_request_transitions end @@ -11,7 +8,7 @@ class ImportRequestTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # import_request_id :bigint # created_at :datetime not null diff --git a/app/models/inventory.rb b/app/models/inventory.rb index 993124b831..2cc7143ee2 100644 --- a/app/models/inventory.rb +++ b/app/models/inventory.rb @@ -3,7 +3,7 @@ class Inventory < ApplicationRecord belongs_to :inventory_file validates :item_identifier, :current_shelf_name, presence: true - validates :item_id, :item_identifier, uniqueness: {scope: :inventory_file_id} + validates :item_id, :item_identifier, uniqueness: { scope: :inventory_file_id } paginates_per 10 @@ -22,14 +22,14 @@ def to_hash end def lost - item.circulation_status = CirculationStatus.find_by(name: 'Missing') + item.circulation_status = CirculationStatus.find_by(name: "Missing") end def found if item.rended? - item.circulation_status = CirculationStatus.find_by(name: 'On Loan') + item.circulation_status = CirculationStatus.find_by(name: "On Loan") else - item.circulation_status = CirculationStatus.find_by(name: 'Available On Shelf') + item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf") end end end diff --git a/app/models/inventory_file.rb b/app/models/inventory_file.rb index 8d7cb123cd..42281ec236 100644 --- a/app/models/inventory_file.rb +++ b/app/models/inventory_file.rb @@ -16,7 +16,7 @@ def import identifier = row.to_s.strip item = Item.find_by(item_identifier: identifier) next unless item - next if self.items.where(id: item.id).select('items.id').first + next if self.items.where(id: item.id).select("items.id").first Inventory.create( inventory_file: self, @@ -30,7 +30,7 @@ def import end def export(col_sep: "\t") - file = Tempfile.create('inventory_file') do |f| + file = Tempfile.create("inventory_file") do |f| inventories.each do |inventory| f.write inventory.to_hash.values.to_csv(col_sep) end @@ -43,7 +43,7 @@ def export(col_sep: "\t") end def missing_items - Item.where(Inventory.where('items.id = inventories.item_id AND inventories.inventory_file_id = ?', id).exists.not) + Item.where(Inventory.where("items.id = inventories.item_id AND inventories.inventory_file_id = ?", id).exists.not) end def found_items diff --git a/app/models/isbn_record.rb b/app/models/isbn_record.rb index 1f364dbec1..41baa4fc92 100644 --- a/app/models/isbn_record.rb +++ b/app/models/isbn_record.rb @@ -11,13 +11,13 @@ def self.new_records(isbn_records_params) isbn_records = [] IsbnRecord.transaction do isbn_records_params.each do |k, v| - next if v['_destroy'] == '1' - if v['body'].present? - isbn_record = IsbnRecord.where(body: Lisbn.new(v['body'].gsub(/[^0-9x]/i, '')).isbn13).first_or_create! - elsif v['id'].present? - isbn_record = IsbnRecord.find(v['id']) + next if v["_destroy"] == "1" + if v["body"].present? + isbn_record = IsbnRecord.where(body: Lisbn.new(v["body"].gsub(/[^0-9x]/i, "")).isbn13).first_or_create! + elsif v["id"].present? + isbn_record = IsbnRecord.find(v["id"]) else - v.delete('_destroy') + v.delete("_destroy") isbn_record = IsbnRecord.create(v) end isbn_records << isbn_record diff --git a/app/models/isbn_record_and_manifestation.rb b/app/models/isbn_record_and_manifestation.rb index cabead5571..8cd857ab2d 100644 --- a/app/models/isbn_record_and_manifestation.rb +++ b/app/models/isbn_record_and_manifestation.rb @@ -1,7 +1,7 @@ class IsbnRecordAndManifestation < ApplicationRecord belongs_to :isbn_record belongs_to :manifestation - validates :isbn_record_id, uniqueness: {scope: :manifestation_id} + validates :isbn_record_id, uniqueness: { scope: :manifestation_id } end # == Schema Information diff --git a/app/models/issn_record.rb b/app/models/issn_record.rb index b3c2ff53c6..15379d2137 100644 --- a/app/models/issn_record.rb +++ b/app/models/issn_record.rb @@ -19,13 +19,13 @@ def self.new_records(issn_records_params) issn_records = [] IssnRecord.transaction do issn_records_params.each do |k, v| - next if v['_destroy'] == '1' - if v['body'].present? - issn_record = IssnRecord.where(body: v['body'].gsub(/[^0-9x]/i, '')).first_or_create! - elsif v['id'].present? - issn_record = IssnRecord.find(v['id']) + next if v["_destroy"] == "1" + if v["body"].present? + issn_record = IssnRecord.where(body: v["body"].gsub(/[^0-9x]/i, "")).first_or_create! + elsif v["id"].present? + issn_record = IssnRecord.find(v["id"]) else - v.delete('_destroy') + v.delete("_destroy") issn_record = IssnRecord.create(v) end issn_records << issn_record diff --git a/app/models/issn_record_and_manifestation.rb b/app/models/issn_record_and_manifestation.rb index 557f3d72e4..855408bbe7 100644 --- a/app/models/issn_record_and_manifestation.rb +++ b/app/models/issn_record_and_manifestation.rb @@ -1,6 +1,7 @@ class IssnRecordAndManifestation < ApplicationRecord belongs_to :issn_record belongs_to :manifestation + validates :issn_record_id, uniqueness: { scope: :manifestation_id } end # == Schema Information diff --git a/app/models/item.rb b/app/models/item.rb index 5723ba23b3..f68c089eea 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -1,10 +1,10 @@ class Item < ApplicationRecord - scope :available, -> { includes(:circulation_status).where.not('circulation_statuses.name' => 'Removed') } - scope :removed, -> { includes(:circulation_status).where('circulation_statuses.name' => 'Removed') } - scope :on_shelf, -> { available.includes(:shelf).references(:shelf).where.not(shelves: { name: 'web' }) } - scope :on_web, -> { available.includes(:shelf).references(:shelf).where('shelves.name = ?', 'web') } + scope :available, -> { includes(:circulation_status).where.not("circulation_statuses.name" => "Removed") } + scope :removed, -> { includes(:circulation_status).where("circulation_statuses.name" => "Removed") } + scope :on_shelf, -> { available.includes(:shelf).references(:shelf).where.not(shelves: { name: "web" }) } + scope :on_web, -> { available.includes(:shelf).references(:shelf).where("shelves.name = ?", "web") } scope :available_for, -> user { - unless user.try(:has_role?, 'Librarian') + unless user.try(:has_role?, "Librarian") on_shelf end } @@ -21,7 +21,7 @@ class Item < ApplicationRecord has_one :resource_import_result belongs_to :manifestation, touch: true belongs_to :bookstore, optional: true - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" belongs_to :budget_type, optional: true has_one :accept, dependent: :destroy has_one :withdraw, dependent: :destroy @@ -30,22 +30,22 @@ class Item < ApplicationRecord belongs_to :shelf, counter_cache: true accepts_nested_attributes_for :item_custom_values, reject_if: :all_blank - scope :accepted_between, lambda{|from, to| includes(:accept).where('items.created_at BETWEEN ? AND ?', Time.zone.parse(from).beginning_of_day, Time.zone.parse(to).end_of_day)} + scope :accepted_between, lambda { |from, to| includes(:accept).where("items.created_at BETWEEN ? AND ?", Time.zone.parse(from).beginning_of_day, Time.zone.parse(to).end_of_day) } validates :item_identifier, allow_blank: true, uniqueness: true, - format: {with: /\A[0-9A-Za-z_]+\Z/} + format: { with: /\A[0-9A-Za-z_]+\Z/ } validates :binding_item_identifier, allow_blank: true, - format: {with: /\A[0-9A-Za-z_]+\Z/} + format: { with: /\A[0-9A-Za-z_]+\Z/ } validates :url, url: true, allow_blank: true, length: { maximum: 255 } validates :acquired_at, date: true, allow_blank: true - strip_attributes only: [:item_identifier, :binding_item_identifier, - :call_number, :binding_call_number, :url] + strip_attributes only: [ :item_identifier, :binding_item_identifier, + :call_number, :binding_call_number, :url ] searchable do text :item_identifier, :note, :title, :creator, :contributor, :publisher, :binding_item_identifier string :item_identifier, multiple: true do - [item_identifier, binding_item_identifier] + [ item_identifier, binding_item_identifier ] end integer :required_role_id integer :manifestation_id @@ -95,7 +95,7 @@ def manifestation_url def removable? if defined?(EnjuCirculation) - return false if circulation_status.name == 'Removed' + return false if circulation_status.name == "Removed" return false if checkouts.exists? true @@ -104,11 +104,11 @@ def removable? end end - def self.csv_header(role: 'Guest') + def self.csv_header(role: "Guest") Item.new.to_hash(role: role).keys end - def to_hash(role: 'Guest') + def to_hash(role: "Guest") record = { item_id: id, item_identifier: item_identifier, @@ -123,7 +123,7 @@ def to_hash(role: 'Guest') item_updated_at: updated_at } - if ['Administrator', 'Librarian'].include?(role) + if [ "Administrator", "Librarian" ].include?(role) record.merge!({ bookstore: bookstore&.name, budget_type: budget_type&.name, diff --git a/app/models/item_custom_value.rb b/app/models/item_custom_value.rb index 806ed84226..7fe8acebef 100644 --- a/app/models/item_custom_value.rb +++ b/app/models/item_custom_value.rb @@ -1,7 +1,7 @@ class ItemCustomValue < ApplicationRecord belongs_to :item_custom_property belongs_to :item - validates :item_custom_property, uniqueness: {scope: :item_id} + validates :item_custom_property, uniqueness: { scope: :item_id } end # == Schema Information diff --git a/app/models/language.rb b/app/models/language.rb index 545df78ebd..1292f5aaf4 100644 --- a/app/models/language.rb +++ b/app/models/language.rb @@ -10,7 +10,7 @@ class Language < ApplicationRecord validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ } def self.available_languages - Language.where(iso_639_1: I18n.available_locales.map{|l| l.to_s}).order(:position) + Language.where(iso_639_1: I18n.available_locales.map { |l| l.to_s }).order(:position) end private diff --git a/app/models/library.rb b/app/models/library.rb index b2e261ad01..8125af6147 100644 --- a/app/models/library.rb +++ b/app/models/library.rb @@ -2,9 +2,9 @@ class Library < ApplicationRecord include MasterModel include EnjuEvent::EnjuLibrary - default_scope { order('libraries.position') } - scope :real, -> { where('id != 1') } - has_many :shelves, -> { order('shelves.position') }, dependent: :destroy, inverse_of: :library + default_scope { order("libraries.position") } + scope :real, -> { where("id != 1") } + has_many :shelves, -> { order("shelves.position") }, dependent: :destroy, inverse_of: :library belongs_to :library_group has_many :profiles, dependent: :restrict_with_exception belongs_to :country, optional: true @@ -66,14 +66,14 @@ def address_changed? has_many :events, dependent: :restrict_with_exception def closed?(date) - events.closing_days.map{ |c| + events.closing_days.map { |c| c.start_at.beginning_of_day }.include?(date.beginning_of_day) end end if defined?(EnjuInterLibraryLoan) - has_many :inter_library_loans, foreign_key: 'borrowing_library_id', inverse_of: :library, dependent: :restrict_with_exception + has_many :inter_library_loans, foreign_key: "borrowing_library_id", inverse_of: :library, dependent: :restrict_with_exception end end diff --git a/app/models/library_group.rb b/app/models/library_group.rb index 920b3c34a1..bdfb783534 100644 --- a/app/models/library_group.rb +++ b/app/models/library_group.rb @@ -1,5 +1,5 @@ class LibraryGroup < ApplicationRecord - #include Singleton + # include Singleton include MasterModel has_many :libraries, dependent: :destroy @@ -12,10 +12,9 @@ class LibraryGroup < ApplicationRecord greater_than_or_equal_to: 0 } accepts_nested_attributes_for :colors, update_only: true - store :settings, accessors: [ + store_accessor :settings, :book_jacket_unknown_resource, - :erms_url - ], coder: JSON + :amazon_hostname translates :login_banner, :footer_banner globalize_accessors @@ -37,7 +36,7 @@ def config? end def real_libraries - libraries.where.not(name: 'web') + libraries.where.not(name: "web") end def network_access_allowed?(ip_address, options = {}) @@ -78,7 +77,7 @@ def network_access_allowed?(ip_address, options = {}) # admin_networks :text # allow_bookmark_external_url :boolean default(FALSE), not null # url :string default("http://localhost:3000/") -# settings :text +# settings :jsonb not null # html_snippet :text # book_jacket_source :string # max_number_of_results :integer default(1000) diff --git a/app/models/loc_search.rb b/app/models/loc_search.rb index c981a73720..10cf8d2792 100644 --- a/app/models/loc_search.rb +++ b/app/models/loc_search.rb @@ -6,8 +6,8 @@ def initialize(node) class ModsRecord < LocSearch MODS_NS = { "mods" => "http://www.loc.gov/mods/v3" } def title - title = @node.xpath('.//mods:titleInfo/mods:title', MODS_NS).first.content - subtitle = @node.xpath('.//mods:titleInfo/mods:subTitle', MODS_NS).first + title = @node.xpath(".//mods:titleInfo/mods:title", MODS_NS).first.content + subtitle = @node.xpath(".//mods:titleInfo/mods:subTitle", MODS_NS).first title += " : #{subtitle.content}" if subtitle title end @@ -25,9 +25,9 @@ def creator if statement_of_responsibility statement_of_responsibility else - names = @node.xpath('.//mods:name', MODS_NS) + names = @node.xpath(".//mods:name", MODS_NS) creator = names.map do |name| - name.xpath('.//mods:namePart', MODS_NS).map do |part| + name.xpath(".//mods:namePart", MODS_NS).map do |part| if part.content part.content else @@ -40,20 +40,20 @@ def creator end def publisher - @node.xpath('.//mods:publisher', MODS_NS).map do |e| + @node.xpath(".//mods:publisher", MODS_NS).map do |e| e.content end.join(", ") end def pubyear - @node.xpath('.//mods:dateIssued', MODS_NS).first.try(:content) + @node.xpath(".//mods:dateIssued", MODS_NS).first.try(:content) end end class DCRecord < LocSearch DC_NS = { "dc" => "http://purl.org/dc/elements/1.1/" } def title - @node.xpath('.//dc:title', DC_NS).first.content + @node.xpath(".//dc:title", DC_NS).first.content end def lccn @@ -76,7 +76,7 @@ def self.make_sru_request_uri(query, options = {}) options = options.merge({ query: query, version: "1.1", operation: "searchRetrieve" }) params = options.map do |k, v| "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}" - end.join('&') + end.join("&") "#{LOC_SRU_BASEURL}?#{params}" end @@ -84,9 +84,9 @@ def self.search(query, options = {}) if query.present? url = make_sru_request_uri(query, options) doc = Nokogiri::XML(Faraday.get(url).body) - items = doc.search('//zs:record').map{|e| ModsRecord.new e } + items = doc.search("//zs:record").map { |e| ModsRecord.new e } @results = { items: items, - total_entries: doc.xpath('//zs:numberOfRecords').first.try(:content).to_i } + total_entries: doc.xpath("//zs:numberOfRecords").first.try(:content).to_i } else { items: [], total_entries: 0 } end @@ -98,7 +98,7 @@ def self.import_from_sru_response(lccn) url = make_sru_request_uri("bath.lccn=\"^#{lccn}\"") response = Nokogiri::XML(Faraday.get(url).body) - record = response.at('//zs:recordData', {"zs" => "http://www.loc.gov/zing/srw/"}) + record = response.at("//zs:recordData", { "zs" => "http://www.loc.gov/zing/srw/" }) return unless record.try(:content) doc = Nokogiri::XML::Document.new diff --git a/app/models/manifestation.rb b/app/models/manifestation.rb index 2db915c6ae..13f2fe51a2 100644 --- a/app/models/manifestation.rb +++ b/app/models/manifestation.rb @@ -8,28 +8,28 @@ class Manifestation < ApplicationRecord include EnjuBookmark::EnjuManifestation include EnjuOai::OaiModel - has_many :creates, -> { order('creates.position') }, dependent: :destroy, foreign_key: 'work_id', inverse_of: :work + has_many :creates, -> { order("creates.position") }, dependent: :destroy, foreign_key: "work_id", inverse_of: :work has_many :creators, through: :creates, source: :agent - has_many :realizes, -> { order('realizes.position') }, dependent: :destroy, foreign_key: 'expression_id', inverse_of: :expression + has_many :realizes, -> { order("realizes.position") }, dependent: :destroy, foreign_key: "expression_id", inverse_of: :expression has_many :contributors, through: :realizes, source: :agent - has_many :produces, -> { order('produces.position') }, dependent: :destroy, foreign_key: 'manifestation_id', inverse_of: :manifestation + has_many :produces, -> { order("produces.position") }, dependent: :destroy, foreign_key: "manifestation_id", inverse_of: :manifestation has_many :publishers, through: :produces, source: :agent has_many :items, dependent: :destroy - has_many :children, foreign_key: 'parent_id', class_name: 'ManifestationRelationship', dependent: :destroy, inverse_of: :parent - has_many :parents, foreign_key: 'child_id', class_name: 'ManifestationRelationship', dependent: :destroy, inverse_of: :child + has_many :children, foreign_key: "parent_id", class_name: "ManifestationRelationship", dependent: :destroy, inverse_of: :parent + has_many :parents, foreign_key: "child_id", class_name: "ManifestationRelationship", dependent: :destroy, inverse_of: :child has_many :derived_manifestations, through: :children, source: :child has_many :original_manifestations, through: :parents, source: :parent has_many :picture_files, as: :picture_attachable, dependent: :destroy belongs_to :language belongs_to :carrier_type - belongs_to :manifestation_content_type, class_name: 'ContentType', foreign_key: 'content_type_id', inverse_of: :manifestations + belongs_to :manifestation_content_type, class_name: "ContentType", foreign_key: "content_type_id", inverse_of: :manifestations has_many :series_statements, dependent: :destroy belongs_to :frequency - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" has_one :resource_import_result has_many :identifiers, dependent: :destroy has_many :manifestation_custom_values, -> { joins(:manifestation_custom_property).order(:position) }, inverse_of: :manifestation, dependent: :destroy - has_one :periodical_record, class_name: 'Periodical', dependent: :destroy + has_one :periodical_record, class_name: "Periodical", dependent: :destroy has_one :periodical_and_manifestation, dependent: :destroy has_one :periodical, through: :periodical_and_manifestation, dependent: :destroy has_many :isbn_record_and_manifestations, dependent: :destroy @@ -59,10 +59,10 @@ class Manifestation < ApplicationRecord text :title, default_boost: 2 do titles end - [:fulltext, :note, :creator, :contributor, :publisher, :abstract, :description, :statement_of_responsibility].each do |field| + [ :fulltext, :note, :creator, :contributor, :publisher, :abstract, :description, :statement_of_responsibility ].each do |field| text field do if series_master? - derived_manifestations.map{|c| c.send(field) }.flatten.compact + derived_manifestations.map { |c| c.send(field) }.flatten.compact else self.send(field) end @@ -80,23 +80,23 @@ class Manifestation < ApplicationRecord end string :title, multiple: true # text フィールドだと区切りのない文字列の index が上手く作成 - #できなかったので。 downcase することにした。 - #他の string 項目も同様の問題があるので、必要な項目は同様の処置が必要。 + # できなかったので。 downcase することにした。 + # 他の string 項目も同様の問題があるので、必要な項目は同様の処置が必要。 string :connect_title do - title.join('').gsub(/\s/, '').downcase + title.join("").gsub(/\s/, "").downcase end string :connect_creator do - creator.join('').gsub(/\s/, '').downcase + creator.join("").gsub(/\s/, "").downcase end string :connect_publisher do - publisher.join('').gsub(/\s/, '').downcase + publisher.join("").gsub(/\s/, "").downcase end string :isbn, multiple: true do isbn_characters end string :issn, multiple: true do if series_statements.exists? - [issn_records.pluck(:body), (series_statements.map{|s| s.manifestation.issn_records.pluck(:body)})].flatten.uniq.compact + [ issn_records.pluck(:body), (series_statements.map { |s| s.manifestation.issn_records.pluck(:body) }) ].flatten.uniq.compact else issn_records.pluck(:body) end @@ -112,9 +112,9 @@ class Manifestation < ApplicationRecord end string :library, multiple: true do if series_master? - root_series_statement.root_manifestation.items.map{|i| i.shelf.library.name}.flatten.uniq + root_series_statement.root_manifestation.items.map { |i| i.shelf.library.name }.flatten.uniq else - items.map{|i| i.shelf.library.name} + items.map { |i| i.shelf.library.name } end end string :language do @@ -128,7 +128,7 @@ class Manifestation < ApplicationRecord end end string :shelf, multiple: true do - items.collect{|i| "#{i.shelf.library.name}_#{i.shelf.name}"} + items.collect { |i| "#{i.shelf.library.name}_#{i.shelf.name}" } end time :created_at time :updated_at @@ -173,7 +173,7 @@ class Manifestation < ApplicationRecord end # OTC start string :creator, multiple: true do - creator.map{|au| au.gsub(' ', '')} + creator.map { |au| au.gsub(" ", "") } end text :au do creator @@ -200,7 +200,7 @@ class Manifestation < ApplicationRecord end text :issn do # 前方一致検索のためtext指定を追加 if series_statements.exists? - [issn_records.pluck(:body), (series_statements.map{|s| s.manifestation.issn_records.pluck(:body)})].flatten.uniq.compact + [ issn_records.pluck(:body), (series_statements.map { |s| s.manifestation.issn_records.pluck(:body) }) ].flatten.uniq.compact else issn_records.pluck(:body) end @@ -230,26 +230,29 @@ class Manifestation < ApplicationRecord end end time :acquired_at + string :agent_id, multiple: true do + creators.map { |a| a.id } + end end has_one_attached :attachment validates :original_title, presence: true - validates :start_page, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :end_page, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :height, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :width, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :depth, numericality: {greater_than_or_equal_to: 0}, allow_blank: true + validates :start_page, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :end_page, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :height, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :width, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :depth, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true validates :manifestation_identifier, uniqueness: true, allow_blank: true - validates :pub_date, format: {with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/}, allow_blank: true - validates :access_address, url: true, allow_blank: true, length: {maximum: 255} - validates :issue_number, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :volume_number, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :serial_number, numericality: {greater_than_or_equal_to: 0}, allow_blank: true - validates :edition, numericality: {greater_than_or_equal_to: 0}, allow_blank: true + validates :pub_date, format: { with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/ }, allow_blank: true + validates :access_address, url: true, allow_blank: true, length: { maximum: 255 } + validates :issue_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :volume_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :serial_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true + validates :edition, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true before_save :set_date_of_publication, :set_number before_save do - attachment.purge if delete_attachment == '1' + attachment.purge if delete_attachment == "1" end after_create :clear_cached_numdocs after_destroy :index_series_statement @@ -259,7 +262,7 @@ class Manifestation < ApplicationRecord manifestation.index_series_statement Sunspot.commit end - strip_attributes only: [:manifestation_identifier, :pub_date, :original_title] + strip_attributes only: [ :manifestation_identifier, :pub_date, :original_title ] paginates_per 10 attr_accessor :during_import, :parent_id, :delete_attachment @@ -277,12 +280,12 @@ def set_date_of_publication date = nil end - pub_date_string = pub_date.rjust(4, "0").split(';').first.gsub(/[\[\]]/, '') + pub_date_string = pub_date.rjust(4, "0").split(";").first.gsub(/[\[\]]/, "") if pub_date_string.length == 4 date = Time.zone.parse(Time.utc(pub_date_string).to_s).beginning_of_day else while date.nil? - pub_date_string += '-01' + pub_date_string += "-01" break if pub_date_string =~ /-01-01-01$/ begin @@ -310,7 +313,7 @@ def set_date_of_publication end def self.cached_numdocs - Rails.cache.fetch("manifestation_search_total"){Manifestation.search.total} + Rails.cache.fetch("manifestation_search_total") { Manifestation.search.total } end def clear_cached_numdocs @@ -336,15 +339,15 @@ def titles title << issue_number_string title << serial_number.to_s title << edition_string - title << series_statements.map{|s| s.titles} - #title << original_title.wakati - #title << title_transcription.wakati rescue nil - #title << title_alternative.wakati rescue nil + title << series_statements.map { |s| s.titles } + # title << original_title.wakati + # title << title_transcription.wakati rescue nil + # title << title_alternative.wakati rescue nil title.flatten end def url - #access_address + # access_address "#{LibraryGroup.site_config.url}#{self.class.to_s.tableize}/#{id}" end @@ -386,30 +389,30 @@ def self.pickup(keyword = nil, current_user = nil) def extract_text return unless attachment.attached? - return unless ENV['ENJU_LEAF_EXTRACT_TEXT'] == 'true' + return unless ENV["ENJU_LEAF_EXTRACT_TEXT"] == "true" - if ENV['ENJU_LEAF_EXTRACT_FILESIZE_LIMIT'].present? - filesize_limit = ENV['ENJU_LEAF_EXTRACT_FILESIZE_LIMIT'].to_i + if ENV["ENJU_LEAF_EXTRACT_FILESIZE_LIMIT"].present? + filesize_limit = ENV["ENJU_LEAF_EXTRACT_FILESIZE_LIMIT"].to_i else filesize_limit = 2097152 end if attachment.byte_size > filesize_limit Rails.logger.error("#{attachment.filename} (size: #{attachment.byte_size} byte(s)) exceeds filesize limit #{ENV['ENJU_LEAF_EXTRACT_FILESIZE_LIMIT']} bytes") - return '' + return "" end - client = Faraday.new(url: ENV['TIKA_URL'] || 'http://tika:9998') do |conn| + client = Faraday.new(url: ENV["TIKA_URL"] || "http://tika:9998") do |conn| conn.adapter :net_http end - response = client.put('/tika/text') do |req| - req.headers['Content-Type'] = attachment.content_type - req.headers['Content-Length'] = attachment.byte_size.to_s + response = client.put("/tika/text") do |req| + req.headers["Content-Type"] = attachment.content_type + req.headers["Content-Length"] = attachment.byte_size.to_s req.body = Faraday::FilePart.new(StringIO.new(attachment.download), attachment.content_type) end - payload = JSON.parse(response.body)['X-TIKA:content'].strip.tr("\t", " ").gsub(/\r?\n/, "") + payload = JSON.parse(response.body)["X-TIKA:content"].strip.tr("\t", " ").gsub(/\r?\n/, "") payload end @@ -428,12 +431,12 @@ def produced(agent) def sort_title if series_master? if root_series_statement.title_transcription? - NKF.nkf('-w --katakana', root_series_statement.title_transcription) + NKF.nkf("-w --katakana", root_series_statement.title_transcription) else root_series_statement.original_title end elsif title_transcription? - NKF.nkf('-w --katakana', title_transcription) + NKF.nkf("-w --katakana", title_transcription) else original_title end @@ -444,7 +447,7 @@ def self.find_by_isbn(isbn) end def index_series_statement - series_statements.map{|s| s.index + series_statements.map { |s| s.index s.root_manifestation&.index} end @@ -462,9 +465,9 @@ def web_item items.find_by(shelf_id: Shelf.web.id) end - def set_agent_role_type(agent_lists, options = {scope: :creator}) + def set_agent_role_type(agent_lists, options = { scope: :creator }) agent_lists.each do |agent_list| - name_and_role = agent_list[:full_name].split('||') + name_and_role = agent_list[:full_name].split("||") if agent_list[:agent_identifier].present? agent = Agent.find_by(agent_identifier: agent_list[:agent_identifier]) end @@ -475,7 +478,7 @@ def set_agent_role_type(agent_lists, options = {scope: :creator}) case options[:scope] when :creator - type = 'author' if type.blank? + type = "author" if type.blank? role_type = CreateType.find_by(name: type) create = Create.find_by(work_id: id, agent_id: agent.id) if create @@ -483,7 +486,7 @@ def set_agent_role_type(agent_lists, options = {scope: :creator}) create.save(validate: false) end when :publisher - type = 'publisher' if role_type.blank? + type = "publisher" if role_type.blank? produce = Produce.find_by(manifestation_id: id, agent_id: agent.id) if produce produce.produce_type = ProduceType.find_by(name: type) @@ -496,19 +499,19 @@ def set_agent_role_type(agent_lists, options = {scope: :creator}) end def set_number - self.volume_number = volume_number_string.scan(/\d*/).map{|s| s.to_i if s =~ /\d/}.compact.first if volume_number_string && !volume_number? - self.issue_number = issue_number_string.scan(/\d*/).map{|s| s.to_i if s =~ /\d/}.compact.first if issue_number_string && !issue_number? - self.edition = edition_string.scan(/\d*/).map{|s| s.to_i if s =~ /\d/}.compact.first if edition_string && !edition? + self.volume_number = volume_number_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if volume_number_string && !volume_number? + self.issue_number = issue_number_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if issue_number_string && !issue_number? + self.edition = edition_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if edition_string && !edition? end def pub_dates return [] unless pub_date - pub_date_array = pub_date.split(';') - pub_date_array.map{|pub_date_string| + pub_date_array = pub_date.split(";") + pub_date_array.map { |pub_date_string| date = nil while date.nil? do - pub_date_string += '-01' + pub_date_string += "-01" break if pub_date_string =~ /-01-01-01$/ begin @@ -523,13 +526,13 @@ def pub_dates def latest_issue if series_master? - derived_manifestations.where.not(date_of_publication: nil).order('date_of_publication DESC').first + derived_manifestations.where.not(date_of_publication: nil).order("date_of_publication DESC").first end end def first_issue if series_master? - derived_manifestations.where.not(date_of_publication: nil).order('date_of_publication DESC').first + derived_manifestations.where.not(date_of_publication: nil).order("date_of_publication DESC").first end end @@ -539,13 +542,13 @@ def identifier_contents(name) # CSVのヘッダ # @param [String] role 権限 - def self.csv_header(role: 'Guest') + def self.csv_header(role: "Guest") Manifestation.new.to_hash(role: role).keys end # CSV出力用のハッシュ # @param [String] role 権限 - def to_hash(role: 'Guest') + def to_hash(role: "Guest") record = { manifestation_id: id, original_title: original_title, @@ -554,27 +557,27 @@ def to_hash(role: 'Guest') statement_of_responsibility: statement_of_responsibility, serial: serial, manifestation_identifier: manifestation_identifier, - creator: creates.map{|create| + creator: creates.map { |create| if create.create_type "#{create.agent.full_name}||#{create.create_type.name}" else "#{create.agent.full_name}" end - }.join('//'), - contributor: realizes.map{|realize| + }.join("//"), + contributor: realizes.map { |realize| if realize.realize_type "#{realize.agent.full_name}||#{realize.realize_type.name}" else "#{realize.agent.full_name}" end - }.join('//'), - publisher: produces.map{|produce| + }.join("//"), + publisher: produces.map { |produce| if produce.produce_type "#{produce.agent.full_name}||#{produce.produce_type.name}" else "#{produce.agent.full_name}" end - }.join('//'), + }.join("//"), pub_date: pub_date, date_of_publication: date_of_publication, year_of_publication: year_of_publication, @@ -585,8 +588,8 @@ def to_hash(role: 'Guest') content_type: manifestation_content_type.name, frequency: frequency.name, language: language.name, - isbn: isbn_records.pluck(:body).join('//'), - issn: issn_records.pluck(:body).join('//'), + isbn: isbn_records.pluck(:body).join("//"), + issn: issn_records.pluck(:body).join("//"), volume_number: volume_number, volume_number_string: volume_number_string, edition: edition, @@ -610,30 +613,30 @@ def to_hash(role: 'Guest') } IdentifierType.find_each do |type| - next if ['isbn', 'issn', 'jpno', 'ncid', 'lccn', 'doi'].include?(type.name.downcase.strip) + next if [ "isbn", "issn", "jpno", "ncid", "lccn", "doi" ].include?(type.name.downcase.strip) - record[:"identifier:#{type.name.to_sym}"] = identifiers.where(identifier_type: type).pluck(:body).join('//') + record[:"identifier:#{type.name.to_sym}"] = identifiers.where(identifier_type: type).pluck(:body).join("//") end series = series_statements.order(:position) record.merge!( - series_statement_id: series.pluck(:id).join('//'), - series_statement_original_title: series.pluck(:original_title).join('.//'), - series_statement_title_subseries: series.pluck(:title_subseries).join('//'), - series_statement_title_subseries_transcription: series.pluck(:title_subseries_transcription).join('//'), - series_statement_title_transcription: series.pluck(:title_transcription).join('//'), - series_statement_creator: series.pluck(:creator_string).join('//'), - series_statement_volume_number: series.pluck(:volume_number_string).join('//'), - series_statement_series_master: series.pluck(:series_master).join('//'), - series_statement_root_manifestation_id: series.pluck(:root_manifestation_id).join('//'), - series_statement_manifestation_id: series.pluck(:manifestation_id).join('//'), - series_statement_position: series.pluck(:position).join('//'), - series_statement_note: series.pluck(:note).join('//'), - series_statement_created_at: series.pluck(:created_at).join('//'), - series_statement_updated_at: series.pluck(:updated_at).join('//') + series_statement_id: series.pluck(:id).join("//"), + series_statement_original_title: series.pluck(:original_title).join(".//"), + series_statement_title_subseries: series.pluck(:title_subseries).join("//"), + series_statement_title_subseries_transcription: series.pluck(:title_subseries_transcription).join("//"), + series_statement_title_transcription: series.pluck(:title_transcription).join("//"), + series_statement_creator: series.pluck(:creator_string).join("//"), + series_statement_volume_number: series.pluck(:volume_number_string).join("//"), + series_statement_series_master: series.pluck(:series_master).join("//"), + series_statement_root_manifestation_id: series.pluck(:root_manifestation_id).join("//"), + series_statement_manifestation_id: series.pluck(:manifestation_id).join("//"), + series_statement_position: series.pluck(:position).join("//"), + series_statement_note: series.pluck(:note).join("//"), + series_statement_created_at: series.pluck(:created_at).join("//"), + series_statement_updated_at: series.pluck(:updated_at).join("//") ) - if ['Administrator', 'Librarian'].include?(role) + if [ "Administrator", "Librarian" ].include?(role) record.merge!({ memo: memo }) @@ -645,10 +648,10 @@ def to_hash(role: 'Guest') if defined?(EnjuSubject) SubjectHeadingType.find_each do |type| - record[:"subject:#{type.name}"] = subjects.where(subject_heading_type: type).pluck(:term).join('//') + record[:"subject:#{type.name}"] = subjects.where(subject_heading_type: type).pluck(:term).join("//") end ClassificationType.find_each do |type| - record[:"classification:#{type.name}"] = classifications.where(classification_type: type).pluck(:category).map(&:to_s).join('//') + record[:"classification:#{type.name}"] = classifications.where(classification_type: type).pluck(:category).map(&:to_s).join("//") end end @@ -664,8 +667,8 @@ def to_hash(role: 'Guest') # TSVでのエクスポート # @param [String] role 権限 # @param [String] col_sep 区切り文字 - def self.export(role: 'Guest', col_sep: "\t") - file = Tempfile.create('manifestation_export') do |f| + def self.export(role: "Guest", col_sep: "\t") + file = Tempfile.create("manifestation_export") do |f| f.write (Manifestation.csv_header(role: role) + Item.csv_header(role: role)).to_csv(col_sep: col_sep) Manifestation.find_each do |manifestation| if manifestation.items.exists? @@ -689,7 +692,7 @@ def root_series_statement end def isbn_characters - isbn_records.pluck(:body).map{|i| + isbn_records.pluck(:body).map { |i| isbn10 = isbn13 = isbn10_dash = isbn13_dash = nil isbn10 = Lisbn.new(i).isbn10 isbn13 = Lisbn.new(i).isbn13 diff --git a/app/models/manifestation_checkout_stat.rb b/app/models/manifestation_checkout_stat.rb index 2d2ac81671..49efd39868 100644 --- a/app/models/manifestation_checkout_stat.rb +++ b/app/models/manifestation_checkout_stat.rb @@ -4,8 +4,8 @@ class ManifestationCheckoutStat < ApplicationRecord initial_state: ManifestationCheckoutStatStateMachine.initial_state ] include CalculateStat - default_scope {order('manifestation_checkout_stats.id DESC')} - scope :not_calculated, -> {in_state(:pending)} + default_scope { order("manifestation_checkout_stats.id DESC") } + scope :not_calculated, -> { in_state(:pending) } has_many :checkout_stat_has_manifestations, dependent: :destroy has_many :manifestations, through: :checkout_stat_has_manifestations belongs_to :user @@ -29,7 +29,7 @@ def calculate_count! # manifestation.update_attributes({daily_checkouts_count: daily_count, total_count: manifestation.total_count + daily_count}) if daily_count.positive? manifestations << manifestation - sql = ['UPDATE checkout_stat_has_manifestations SET checkouts_count = ? WHERE manifestation_checkout_stat_id = ? AND manifestation_id = ?', daily_count, id, manifestation.id] + sql = [ "UPDATE checkout_stat_has_manifestations SET checkouts_count = ? WHERE manifestation_checkout_stat_id = ? AND manifestation_id = ?", daily_count, id, manifestation.id ] ManifestationCheckoutStat.connection.execute( self.class.send(:sanitize_sql_array, sql) ) diff --git a/app/models/manifestation_checkout_stat_transition.rb b/app/models/manifestation_checkout_stat_transition.rb index f980d01d8a..2769754004 100644 --- a/app/models/manifestation_checkout_stat_transition.rb +++ b/app/models/manifestation_checkout_stat_transition.rb @@ -1,7 +1,4 @@ class ManifestationCheckoutStatTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :manifestation_checkout_stat, inverse_of: :manifestation_checkout_stat_transitions end @@ -11,7 +8,7 @@ class ManifestationCheckoutStatTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # manifestation_checkout_stat_id :bigint # created_at :datetime not null diff --git a/app/models/manifestation_custom_value.rb b/app/models/manifestation_custom_value.rb index c3c6618b36..79847dacaf 100644 --- a/app/models/manifestation_custom_value.rb +++ b/app/models/manifestation_custom_value.rb @@ -1,7 +1,7 @@ class ManifestationCustomValue < ApplicationRecord belongs_to :manifestation_custom_property belongs_to :manifestation - validates :manifestation_custom_property, uniqueness: {scope: :manifestation_id} + validates :manifestation_custom_property, uniqueness: { scope: :manifestation_id } end # == Schema Information diff --git a/app/models/manifestation_relationship.rb b/app/models/manifestation_relationship.rb index 7d7c60c5b5..427124013d 100644 --- a/app/models/manifestation_relationship.rb +++ b/app/models/manifestation_relationship.rb @@ -1,6 +1,6 @@ class ManifestationRelationship < ApplicationRecord - belongs_to :parent, class_name: 'Manifestation' - belongs_to :child, class_name: 'Manifestation' + belongs_to :parent, class_name: "Manifestation" + belongs_to :child, class_name: "Manifestation" belongs_to :manifestation_relationship_type, optional: true validate :check_parent acts_as_list scope: :parent_id diff --git a/app/models/manifestation_relationship_type.rb b/app/models/manifestation_relationship_type.rb index d7d31920bb..e7909eacb2 100644 --- a/app/models/manifestation_relationship_type.rb +++ b/app/models/manifestation_relationship_type.rb @@ -1,6 +1,6 @@ class ManifestationRelationshipType < ApplicationRecord include MasterModel - default_scope { order('manifestation_relationship_types.position') } + default_scope { order("manifestation_relationship_types.position") } has_many :manifestation_relationships, dependent: :destroy end diff --git a/app/models/manifestation_reserve_stat.rb b/app/models/manifestation_reserve_stat.rb index 806411f0b3..297df72564 100644 --- a/app/models/manifestation_reserve_stat.rb +++ b/app/models/manifestation_reserve_stat.rb @@ -4,8 +4,8 @@ class ManifestationReserveStat < ApplicationRecord initial_state: ManifestationReserveStatStateMachine.initial_state ] include CalculateStat - default_scope {order('manifestation_reserve_stats.id DESC')} - scope :not_calculated, -> {in_state(:pending)} + default_scope { order("manifestation_reserve_stats.id DESC") } + scope :not_calculated, -> { in_state(:pending) } has_many :reserve_stat_has_manifestations, dependent: :destroy has_many :manifestations, through: :reserve_stat_has_manifestations belongs_to :user @@ -29,7 +29,7 @@ def calculate_count! # manifestation.update_attributes({daily_reserves_count: daily_count, total_count: manifestation.total_count + daily_count}) if daily_count.positive? manifestations << manifestation - sql = ['UPDATE reserve_stat_has_manifestations SET reserves_count = ? WHERE manifestation_reserve_stat_id = ? AND manifestation_id = ?', daily_count, id, manifestation.id] + sql = [ "UPDATE reserve_stat_has_manifestations SET reserves_count = ? WHERE manifestation_reserve_stat_id = ? AND manifestation_id = ?", daily_count, id, manifestation.id ] ManifestationReserveStat.connection.execute( self.class.send(:sanitize_sql_array, sql) ) diff --git a/app/models/manifestation_reserve_stat_transition.rb b/app/models/manifestation_reserve_stat_transition.rb index 1f68dd0fee..5993255765 100644 --- a/app/models/manifestation_reserve_stat_transition.rb +++ b/app/models/manifestation_reserve_stat_transition.rb @@ -1,7 +1,4 @@ class ManifestationReserveStatTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :manifestation_reserve_stat, inverse_of: :manifestation_reserve_stat_transitions end @@ -11,7 +8,7 @@ class ManifestationReserveStatTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # manifestation_reserve_stat_id :bigint # created_at :datetime not null diff --git a/app/models/medium_of_performance.rb b/app/models/medium_of_performance.rb index a989f08325..d34f0eda9e 100644 --- a/app/models/medium_of_performance.rb +++ b/app/models/medium_of_performance.rb @@ -1,6 +1,6 @@ class MediumOfPerformance < ApplicationRecord include MasterModel - has_many :works, class_name: 'Manifestation' + has_many :works, class_name: "Manifestation" end # == Schema Information diff --git a/app/models/message.rb b/app/models/message.rb index 2b21b79278..b349a05d62 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -3,9 +3,9 @@ class Message < ApplicationRecord transition_class: MessageTransition, initial_state: MessageStateMachine.initial_state ] - scope :unread, -> {in_state('unread')} - belongs_to :sender, class_name: 'User' - belongs_to :receiver, class_name: 'User' + scope :unread, -> { in_state("unread") } + belongs_to :sender, class_name: "User" + belongs_to :receiver, class_name: "User" validates :subject, :body, presence: true # , :sender validates :receiver, presence: { message: :invalid } before_validation :set_receiver @@ -58,7 +58,7 @@ def read end def read? - return true if current_state == 'read' + return true if current_state == "read" false end diff --git a/app/models/message_transition.rb b/app/models/message_transition.rb index 9928c8707a..948eaa8e52 100644 --- a/app/models/message_transition.rb +++ b/app/models/message_transition.rb @@ -1,6 +1,4 @@ class MessageTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - belongs_to :message, inverse_of: :message_transitions end @@ -10,7 +8,7 @@ class MessageTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # message_id :bigint # created_at :datetime not null diff --git a/app/models/ndl_book.rb b/app/models/ndl_book.rb index 294b280e63..488ad895a2 100644 --- a/app/models/ndl_book.rb +++ b/app/models/ndl_book.rb @@ -8,31 +8,31 @@ def jpno end def permalink - @node.at('./link').try(:content).to_s + @node.at("./link").try(:content).to_s end def itemno - URI.parse(permalink).path.split('/').last + URI.parse(permalink).path.split("/").last end def title - @node.at('./title').try(:content).to_s + @node.at("./title").try(:content).to_s end def volume - @node.at('./dcndl:volume').try(:content).to_s + @node.at("./dcndl:volume").try(:content).to_s end def series_title - @node.at('./dcndl:seriesTitle').try(:content).to_s + @node.at("./dcndl:seriesTitle").try(:content).to_s end def creator - @node.xpath('./dc:creator').map(&:content).join(' ') + @node.xpath("./dc:creator").map(&:content).join(" ") end def publisher - @node.xpath('./dc:publisher').map(&:content).join(' ') + @node.xpath("./dc:publisher").map(&:content).join(" ") end def issued @@ -52,13 +52,13 @@ def self.search(query, page = 1, _per_page = per_page) cnt = per_page page = 1 if page.to_i < 1 idx = (page.to_i - 1) * cnt + 1 - doc = Nokogiri::XML(Manifestation.search_ndl(query, cnt: cnt, page: page, idx: idx, raw: true, mediatype: 'books periodicals video audio scores').to_s) - items = doc.xpath('//channel/item').map{|node| new node } - total_entries = doc.at('//channel/openSearch:totalResults').content.to_i + doc = Nokogiri::XML(Manifestation.search_ndl(query, cnt: cnt, page: page, idx: idx, raw: true, mediatype: "books periodicals video audio scores").to_s) + items = doc.xpath("//channel/item").map { |node| new node } + total_entries = doc.at("//channel/openSearch:totalResults").content.to_i - {items: items, total_entries: total_entries} + { items: items, total_entries: total_entries } else - {items: [], total_entries: 0} + { items: [], total_entries: 0 } end end @@ -68,23 +68,23 @@ def self.import_from_sru_response(itemno) url = "https://ndlsearch.ndl.go.jp/api/sru?operation=searchRetrieve&recordSchema=dcndl&maximumRecords=1&query=%28itemno=#{itemno}%29&onlyBib=true" xml = Faraday.get(url).body - response = Nokogiri::XML(xml).at('//xmlns:recordData') + response = Nokogiri::XML(xml).at("//xmlns:recordData") return unless response.try(:content) Manifestation.import_record(Nokogiri::XML(response.content)) end def subjects - @node.xpath('//dcterms:subject/rdf:Description').map{|a| + @node.xpath("//dcterms:subject/rdf:Description").map { |a| { - id: a.attributes['about'].content, - value: a.at('./rdf:value').content + id: a.attributes["about"].content, + value: a.at("./rdf:value").content } } end def authors - @node.xpath('//dcterms:creator/foaf:Agent').map{|a| {id: a.attributes['about'].content, name: a.at('./foaf:name').content, transcription: a.at('./dcndl:transcription').try(:content)}} + @node.xpath("//dcterms:creator/foaf:Agent").map { |a| { id: a.attributes["about"].content, name: a.at("./foaf:name").content, transcription: a.at("./dcndl:transcription").try(:content) } } end attr_accessor :url diff --git a/app/models/news_feed.rb b/app/models/news_feed.rb index 2cfc8618c8..dfac4d7847 100644 --- a/app/models/news_feed.rb +++ b/app/models/news_feed.rb @@ -14,7 +14,7 @@ def self.per_page def fetch begin - feed = Faraday.get(url).body.force_encoding('UTF-8') + feed = Faraday.get(url).body.force_encoding("UTF-8") if RSS::Parser.parse(feed, false) self.body = feed end diff --git a/app/models/news_post.rb b/app/models/news_post.rb index 5331cca410..cbd0264d94 100644 --- a/app/models/news_post.rb +++ b/app/models/news_post.rb @@ -1,9 +1,9 @@ class NewsPost < ApplicationRecord scope :published, -> { where(draft: false) } - scope :current, -> { where('start_date <= ? AND end_date >= ?', Time.zone.now, Time.zone.now) } - default_scope { order('news_posts.start_date DESC') } + scope :current, -> { where("start_date <= ? AND end_date >= ?", Time.zone.now, Time.zone.now) } + default_scope { order("news_posts.start_date DESC") } belongs_to :user - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" validates :title, :body, presence: true validate :check_date diff --git a/app/models/order_list.rb b/app/models/order_list.rb index 54ce1bb822..3eb2a7eecf 100644 --- a/app/models/order_list.rb +++ b/app/models/order_list.rb @@ -3,7 +3,7 @@ class OrderList < ApplicationRecord transition_class: OrderListTransition, initial_state: :pending ] - scope :not_ordered, -> {in_state(:not_ordered)} + scope :not_ordered, -> { in_state(:not_ordered) } has_many :orders, dependent: :destroy has_many :purchase_requests, through: :orders @@ -40,7 +40,7 @@ def order end def ordered? - true if current_state == 'ordered' + true if current_state == "ordered" end end diff --git a/app/models/order_list_transition.rb b/app/models/order_list_transition.rb index e29c009bf8..0bc468f34e 100644 --- a/app/models/order_list_transition.rb +++ b/app/models/order_list_transition.rb @@ -1,7 +1,4 @@ class OrderListTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :order_list, inverse_of: :order_list_transitions end @@ -11,7 +8,7 @@ class OrderListTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # order_list_id :integer # created_at :datetime not null diff --git a/app/models/picture_file.rb b/app/models/picture_file.rb index 0bf006413a..94e929f74e 100644 --- a/app/models/picture_file.rb +++ b/app/models/picture_file.rb @@ -4,9 +4,9 @@ class PictureFile < ApplicationRecord has_one_attached :attachment - validates :picture_attachable_type, presence: true, inclusion: { in: ['Event', 'Manifestation', 'Agent', 'Shelf'] } + validates :picture_attachable_type, presence: true, inclusion: { in: [ "Event", "Manifestation", "Agent", "Shelf" ] } validates_associated :picture_attachable - default_scope { order('picture_files.position') } + default_scope { order("picture_files.position") } # http://railsforum.com/viewtopic.php?id=11615 acts_as_list scope: :picture_attachable strip_attributes only: :picture_attachable_type diff --git a/app/models/produce_type.rb b/app/models/produce_type.rb index d607428072..d5c1728345 100644 --- a/app/models/produce_type.rb +++ b/app/models/produce_type.rb @@ -1,6 +1,6 @@ class ProduceType < ApplicationRecord include MasterModel - default_scope { order('produce_types.position') } + default_scope { order("produce_types.position") } end # == Schema Information diff --git a/app/models/profile.rb b/app/models/profile.rb index 42a10b2eaa..cd66292403 100644 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -1,11 +1,11 @@ class Profile < ApplicationRecord include EnjuCirculation::EnjuProfile - scope :administrators, -> { joins(user: :role).where('roles.name = ?', 'Administrator') } - scope :librarians, -> { joins(user: :role).where('roles.name = ? OR roles.name = ?', 'Administrator', 'Librarian') } + scope :administrators, -> { joins(user: :role).where("roles.name = ?", "Administrator") } + scope :librarians, -> { joins(user: :role).where("roles.name = ? OR roles.name = ?", "Administrator", "Librarian") } belongs_to :user, optional: true belongs_to :library belongs_to :user_group - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" has_many :identities, dependent: :destroy has_many :agents, dependent: :nullify accepts_nested_attributes_for :identities, allow_destroy: true, reject_if: :all_blank @@ -49,7 +49,7 @@ class Profile < ApplicationRecord # 既定のユーザ権限を設定します。 # @return [void] def set_role_and_agent - self.required_role = Role.find_by(name: 'Librarian') unless required_role + self.required_role = Role.find_by(name: "Librarian") unless required_role self.locale = I18n.default_locale.to_s unless locale end diff --git a/app/models/purchase_request.rb b/app/models/purchase_request.rb index 1a973b931c..bf25a5b7c4 100644 --- a/app/models/purchase_request.rb +++ b/app/models/purchase_request.rb @@ -1,6 +1,6 @@ class PurchaseRequest < ApplicationRecord - scope :not_ordered, -> {includes(:order_list).where('order_lists.ordered_at IS NULL') } - scope :ordered, -> { includes(:order_list).where('order_lists.ordered_at IS NOT NULL') } + scope :not_ordered, -> { includes(:order_list).where("order_lists.ordered_at IS NULL") } + scope :ordered, -> { includes(:order_list).where("order_lists.ordered_at IS NOT NULL") } belongs_to :user, validate: true has_one :order, dependent: :destroy @@ -9,12 +9,12 @@ class PurchaseRequest < ApplicationRecord validates_associated :user validates_presence_of :user, :title validate :check_price - validates :url, url: true, allow_blank: true, length: {maximum: 255} + validates :url, url: true, allow_blank: true, length: { maximum: 255 } after_destroy :index! after_save :index! before_save :set_date_of_publication - strip_attributes only: [:url, :pub_date] + strip_attributes only: [ :url, :pub_date ] searchable do text :title, :author, :publisher, :url @@ -32,7 +32,7 @@ class PurchaseRequest < ApplicationRecord time :accepted_at time :denied_at boolean :ordered do - if order_list.try(:current_state) == 'ordered' + if order_list.try(:current_state) == "ordered" true else false diff --git a/app/models/realize.rb b/app/models/realize.rb index f969a530f4..c810c7c57a 100644 --- a/app/models/realize.rb +++ b/app/models/realize.rb @@ -1,6 +1,6 @@ class Realize < ApplicationRecord belongs_to :agent - belongs_to :expression, class_name: 'Manifestation', touch: true + belongs_to :expression, class_name: "Manifestation", touch: true belongs_to :realize_type, optional: true validates :expression_id, uniqueness: { scope: :agent_id } diff --git a/app/models/realize_type.rb b/app/models/realize_type.rb index bf5f5e6628..cc8d92b016 100644 --- a/app/models/realize_type.rb +++ b/app/models/realize_type.rb @@ -1,6 +1,6 @@ class RealizeType < ApplicationRecord include MasterModel - default_scope { order('realize_types.position') } + default_scope { order("realize_types.position") } end # == Schema Information diff --git a/app/models/reserve.rb b/app/models/reserve.rb index d302200bc5..10959be71e 100644 --- a/app/models/reserve.rb +++ b/app/models/reserve.rb @@ -5,31 +5,31 @@ class Reserve < ApplicationRecord ] scope :hold, -> { where.not(item_id: nil) } scope :not_hold, -> { where(item_id: nil) } - scope :waiting, -> {not_in_state(:completed, :canceled, :expired).where('canceled_at IS NULL AND (expired_at > ? OR expired_at IS NULL)', Time.zone.now).order('reserves.id DESC')} - scope :retained, -> {in_state(:retained).where.not(retained_at: nil)} - scope :completed, -> {in_state(:completed).where.not(checked_out_at: nil)} - scope :canceled, -> {in_state(:canceled).where.not(canceled_at: nil)} - scope :postponed, -> {in_state(:postponed).where.not(postponed_at: nil)} - scope :will_expire_retained, lambda {|datetime| in_state(:retained).where('checked_out_at IS NULL AND canceled_at IS NULL AND expired_at <= ?', datetime).order('expired_at')} - scope :will_expire_pending, lambda {|datetime| in_state(:pending).where('checked_out_at IS NULL AND canceled_at IS NULL AND expired_at <= ?', datetime).order('expired_at')} - scope :created, lambda {|start_date, end_date| where('created_at >= ? AND created_at < ?', start_date, end_date)} - scope :not_sent_expiration_notice_to_patron, -> {in_state(:expired).where(expiration_notice_to_patron: false)} - scope :not_sent_expiration_notice_to_library, -> {in_state(:expired).where(expiration_notice_to_library: false)} - scope :sent_expiration_notice_to_patron, -> {in_state(:expired).where(expiration_notice_to_patron: true)} - scope :sent_expiration_notice_to_library, -> {in_state(:expired).where(expiration_notice_to_library: true)} - scope :not_sent_cancel_notice_to_patron, -> {in_state(:canceled).where(expiration_notice_to_patron: false)} - scope :not_sent_cancel_notice_to_library, -> {in_state(:canceled).where(expiration_notice_to_library: false)} + scope :waiting, -> { not_in_state(:completed, :canceled, :expired).where("canceled_at IS NULL AND (expired_at > ? OR expired_at IS NULL)", Time.zone.now) } + scope :retained, -> { in_state(:retained).where.not(retained_at: nil) } + scope :completed, -> { in_state(:completed).where.not(checked_out_at: nil) } + scope :canceled, -> { in_state(:canceled).where.not(canceled_at: nil) } + scope :postponed, -> { in_state(:postponed).where.not(postponed_at: nil) } + scope :will_expire_retained, lambda { |datetime| in_state(:retained).where("checked_out_at IS NULL AND canceled_at IS NULL AND expired_at <= ?", datetime).order("expired_at") } + scope :will_expire_pending, lambda { |datetime| in_state(:pending).where("checked_out_at IS NULL AND canceled_at IS NULL AND expired_at <= ?", datetime).order("expired_at") } + scope :created, lambda { |start_date, end_date| where("created_at >= ? AND created_at < ?", start_date, end_date) } + scope :not_sent_expiration_notice_to_patron, -> { in_state(:expired).where(expiration_notice_to_patron: false) } + scope :not_sent_expiration_notice_to_library, -> { in_state(:expired).where(expiration_notice_to_library: false) } + scope :sent_expiration_notice_to_patron, -> { in_state(:expired).where(expiration_notice_to_patron: true) } + scope :sent_expiration_notice_to_library, -> { in_state(:expired).where(expiration_notice_to_library: true) } + scope :not_sent_cancel_notice_to_patron, -> { in_state(:canceled).where(expiration_notice_to_patron: false) } + scope :not_sent_cancel_notice_to_library, -> { in_state(:canceled).where(expiration_notice_to_library: false) } belongs_to :user belongs_to :manifestation, touch: true - belongs_to :librarian, class_name: 'User', optional: true + belongs_to :librarian, class_name: "User", optional: true belongs_to :item, touch: true, optional: true belongs_to :request_status_type - belongs_to :pickup_location, class_name: 'Library', optional: true + belongs_to :pickup_location, class_name: "Library", optional: true validates :expired_at, date: true, allow_blank: true validate :manifestation_must_include_item validate :available_for_reservation?, on: :create - validates :item_id, presence: true, if: proc{|reserve| + validates :item_id, presence: true, if: proc { |reserve| if item_id_changed? if reserve.completed? || reserve.retained? if item_id_change[0] @@ -60,7 +60,7 @@ class Reserve < ApplicationRecord after_save do if item - item.checkouts.map{|checkout| checkout.index} + item.checkouts.map { |checkout| checkout.index } Sunspot.commit end end @@ -129,38 +129,36 @@ def set_user def valid_item? if item_identifier.present? item = Item.find_by(item_identifier: item_identifier) - errors.add(:base, I18n.t('reserve.invalid_item')) unless item + errors.add(:base, I18n.t("reserve.invalid_item")) unless item end end def retained_by_other_user? - return nil if force_retaining == '1' + return nil if force_retaining == "1" if item && !retained? if Reserve.retained.where(item_id: item.id).count.positive? - errors.add(:base, I18n.t('reserve.attempt_to_update_retained_reservation')) + errors.add(:base, I18n.t("reserve.attempt_to_update_retained_reservation")) end end end def set_request_status - self.request_status_type = RequestStatusType.find_by(name: 'In Process') + self.request_status_type = RequestStatusType.find_by(name: "In Process") end def check_expired_at if canceled_at.blank? && expired_at? unless completed? if expired_at.beginning_of_day < Time.zone.now - errors.add(:base, I18n.t('reserve.invalid_date')) + errors.add(:base, I18n.t("reserve.invalid_date")) end end end end def next_reservation - if item - Reserve.waiting.where(manifestation_id: item.manifestation.id).readonly(false).first - end + Reserve.waiting.where.not(id: id).order(:created_at).find_by(manifestation_id: manifestation_id) end def send_message(sender = nil) @@ -169,18 +167,18 @@ def send_message(sender = nil) mailer = nil case current_state - when 'requested' + when "requested" mailer = ReserveMailer.accepted(self) - when 'canceled' + when "canceled" mailer = ReserveMailer.canceled(self) - when 'expired' + when "expired" mailer = ReserveMailer.expired(self) - when 'retained' + when "retained" mailer = ReserveMailer.retained(self) - when 'postponed' + when "postponed" mailer = ReserveMailer.postponed(self) else - raise 'status not defined' + raise "status not defined" end if mailer @@ -204,11 +202,11 @@ def send_message(sender = nil) def self.expire Reserve.transaction do - will_expire_retained(Time.zone.now.beginning_of_day).readonly(false).map{|r| + will_expire_retained(Time.zone.now.beginning_of_day).readonly(false).map { |r| r.transition_to!(:expired) r.send_message } - will_expire_pending(Time.zone.now.beginning_of_day).readonly(false).map{|r| + will_expire_pending(Time.zone.now.beginning_of_day).readonly(false).map { |r| r.transition_to!(:expired) r.send_message } @@ -217,36 +215,36 @@ def self.expire def checked_out_now? if user && manifestation - true unless (user.checkouts.not_returned.pluck(:item_id) & manifestation.items.pluck('items.id')).empty? + true unless (user.checkouts.not_returned.pluck(:item_id) & manifestation.items.pluck("items.id")).empty? end end def available_for_reservation? if manifestation if checked_out_now? - errors.add(:base, I18n.t('reserve.this_manifestation_is_already_checked_out')) + errors.add(:base, I18n.t("reserve.this_manifestation_is_already_checked_out")) end if manifestation.is_reserved_by?(user) - errors.add(:base, I18n.t('reserve.this_manifestation_is_already_reserved')) + errors.add(:base, I18n.t("reserve.this_manifestation_is_already_reserved")) end if user.try(:reached_reservation_limit?, manifestation) - errors.add(:base, I18n.t('reserve.excessed_reservation_limit')) + errors.add(:base, I18n.t("reserve.excessed_reservation_limit")) end expired_period = manifestation.try(:reservation_expired_period, user) if expired_period.nil? - errors.add(:base, I18n.t('reserve.this_patron_cannot_reserve')) + errors.add(:base, I18n.t("reserve.this_patron_cannot_reserve")) end end end def completed? - ['canceled', 'expired', 'completed'].include?(current_state) + [ "canceled", "expired", "completed" ].include?(current_state) end def retained? - return true if current_state == 'retained' + return true if current_state == "retained" false end @@ -254,13 +252,13 @@ def retained? private def do_request - assign_attributes(request_status_type: RequestStatusType.find_by(name: 'In Process'), item_id: nil, retained_at: nil) + assign_attributes(request_status_type: RequestStatusType.find_by(name: "In Process"), item_id: nil, retained_at: nil) save! end def retain # TODO: 「取り置き中」の状態を正しく表す - assign_attributes(request_status_type: RequestStatusType.find_by(name: 'In Process'), retained_at: Time.zone.now) + assign_attributes(request_status_type: RequestStatusType.find_by(name: "In Process"), retained_at: Time.zone.now) Reserve.transaction do item.next_reservation.try(:transition_to!, :postponed) save! @@ -269,7 +267,7 @@ def retain def expire Reserve.transaction do - assign_attributes(request_status_type: RequestStatusType.find_by(name: 'Expired'), canceled_at: Time.zone.now) + assign_attributes(request_status_type: RequestStatusType.find_by(name: "Expired"), canceled_at: Time.zone.now) reserve = next_reservation if reserve reserve.item = item @@ -283,7 +281,7 @@ def expire def cancel Reserve.transaction do - assign_attributes(request_status_type: RequestStatusType.find_by(name: 'Cannot Fulfill Request'), canceled_at: Time.zone.now) + assign_attributes(request_status_type: RequestStatusType.find_by(name: "Cannot Fulfill Request"), canceled_at: Time.zone.now) save! reserve = next_reservation if reserve @@ -296,13 +294,13 @@ def cancel end def checkout - assign_attributes(request_status_type: RequestStatusType.find_by(name: 'Available For Pickup'), checked_out_at: Time.zone.now) + assign_attributes(request_status_type: RequestStatusType.find_by(name: "Available For Pickup"), checked_out_at: Time.zone.now) save! end def postpone assign_attributes( - request_status_type: RequestStatusType.find_by(name: 'In Process'), + request_status_type: RequestStatusType.find_by(name: "In Process"), item_id: nil, retained_at: nil, postponed_at: Time.zone.now @@ -312,7 +310,7 @@ def postpone def manifestation_must_include_item if manifestation && item && !completed? - errors.add(:base, I18n.t('reserve.invalid_item')) unless manifestation.items.include?(item) + errors.add(:base, I18n.t("reserve.invalid_item")) unless manifestation.items.include?(item) end end diff --git a/app/models/reserve_state_machine.rb b/app/models/reserve_state_machine.rb index a233ae9448..29dc19525b 100644 --- a/app/models/reserve_state_machine.rb +++ b/app/models/reserve_state_machine.rb @@ -8,27 +8,26 @@ class ReserveStateMachine state :expired state :completed - transition from: :pending, to: [:requested] - transition from: :postponed, to: [:requested, :retained, :canceled, :expired] - transition from: :retained, to: [:postponed, :canceled, :expired, :completed] - transition from: :requested, to: [:retained, :canceled, :expired, :completed] + transition from: :pending, to: [ :requested ] + transition from: :postponed, to: [ :requested, :retained, :canceled, :expired ] + transition from: :retained, to: [ :postponed, :canceled, :expired, :completed ] + transition from: :requested, to: [ :retained, :canceled, :expired, :completed ] after_transition(to: :requested) do |reserve| - reserve.update(request_status_type: RequestStatusType.find_by(name: 'In Process'), item_id: nil, retained_at: nil) + reserve.update(request_status_type: RequestStatusType.find_by(name: "In Process"), item_id: nil, retained_at: nil) end after_transition(to: :retained) do |reserve| # TODO: 「取り置き中」の状態を正しく表す - reserve.update(request_status_type: RequestStatusType.find_by(name: 'In Process'), retained_at: Time.zone.now) + reserve.update(request_status_type: RequestStatusType.find_by(name: "In Process"), retained_at: Time.zone.now) Reserve.transaction do if reserve.item other_reserves = reserve.item.reserves.waiting - other_reserves.each{|r| + other_reserves.each { |r| next unless r != reserve r.transition_to!(:postponed) - r.item = nil - r.save! + r.update!(item: nil) } end end @@ -36,12 +35,11 @@ class ReserveStateMachine after_transition(to: :canceled) do |reserve| Reserve.transaction do - reserve.update(request_status_type: RequestStatusType.find_by(name: 'Cannot Fulfill Request'), canceled_at: Time.zone.now) + reserve.update(request_status_type: RequestStatusType.find_by(name: "Cannot Fulfill Request"), canceled_at: Time.zone.now) next_reserve = reserve.next_reservation if next_reserve next_reserve.item = reserve.item - reserve.item = nil - reserve.save! + reserve.update!(item: nil) next_reserve.transition_to!(:retained) end end @@ -49,13 +47,12 @@ class ReserveStateMachine after_transition(to: :expired) do |reserve| Reserve.transaction do - reserve.update(request_status_type: RequestStatusType.find_by(name: 'Expired'), canceled_at: Time.zone.now) + reserve.update(request_status_type: RequestStatusType.find_by(name: "Expired"), canceled_at: Time.zone.now) next_reserve = reserve.next_reservation if next_reserve next_reserve.item = reserve.item next_reserve.transition_to!(:retained) - reserve.item = nil - reserve.save! + reserve.update!(item: nil) end end Rails.logger.info "#{Time.zone.now} reserve_id #{reserve.id} expired!" @@ -67,7 +64,7 @@ class ReserveStateMachine after_transition(to: :completed) do |reserve| reserve.update( - request_status_type: RequestStatusType.find_by(name: 'Available For Pickup'), + request_status_type: RequestStatusType.find_by(name: "Available For Pickup"), checked_out_at: Time.zone.now ) end diff --git a/app/models/reserve_transition.rb b/app/models/reserve_transition.rb index e53fa19b03..f05161dd5e 100644 --- a/app/models/reserve_transition.rb +++ b/app/models/reserve_transition.rb @@ -1,7 +1,4 @@ class ReserveTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :reserve, inverse_of: :reserve_transitions end @@ -11,7 +8,7 @@ class ReserveTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # reserve_id :bigint # created_at :datetime not null diff --git a/app/models/resource_export_file.rb b/app/models/resource_export_file.rb index cad0a4b4a4..0d53eef376 100644 --- a/app/models/resource_export_file.rb +++ b/app/models/resource_export_file.rb @@ -22,7 +22,7 @@ def export! tsv = Manifestation.export(role: role_name) file = StringIO.new(tsv) # file.class.class_eval { attr_accessor :original_filename, :content_type } - attachment.attach(io: file, filename: 'resource_export.txt') + attachment.attach(io: file, filename: "resource_export.txt") save! transition_to!(:completed) mailer = ResourceExportMailer.completed(self) diff --git a/app/models/resource_export_file_state_machine.rb b/app/models/resource_export_file_state_machine.rb index 7635570580..898bf56f0f 100644 --- a/app/models/resource_export_file_state_machine.rb +++ b/app/models/resource_export_file_state_machine.rb @@ -6,8 +6,8 @@ class ResourceExportFileStateMachine state :completed state :failed - transition from: :pending, to: [:started, :failed] - transition from: :started, to: [:completed, :failed] + transition from: :pending, to: [ :started, :failed ] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |resource_export_file| resource_export_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/resource_export_file_transition.rb b/app/models/resource_export_file_transition.rb index 074d4bfea1..57b50f1dd2 100644 --- a/app/models/resource_export_file_transition.rb +++ b/app/models/resource_export_file_transition.rb @@ -1,7 +1,4 @@ class ResourceExportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :resource_export_file, inverse_of: :resource_export_file_transitions end @@ -11,7 +8,7 @@ class ResourceExportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # resource_export_file_id :bigint # created_at :datetime not null diff --git a/app/models/resource_import_file.rb b/app/models/resource_import_file.rb index 83ae1daa5f..562552155b 100644 --- a/app/models/resource_import_file.rb +++ b/app/models/resource_import_file.rb @@ -4,14 +4,14 @@ class ResourceImportFile < ApplicationRecord initial_state: ResourceImportFileStateMachine.initial_state ] include ImportFile - default_scope { order('resource_import_files.id DESC') } + default_scope { order("resource_import_files.id DESC") } scope :not_imported, -> { in_state(:pending) } - scope :stucked, -> { in_state(:pending).where('resource_import_files.created_at < ?', 1.hour.ago) } + scope :stucked, -> { in_state(:pending).where("resource_import_files.created_at < ?", 1.hour.ago) } has_one_attached :attachment - validates :default_shelf_id, presence: true, if: proc{|model| model.edit_mode == 'create'} + validates :default_shelf_id, presence: true, if: proc { |model| model.edit_mode == "create" } belongs_to :user - belongs_to :default_shelf, class_name: 'Shelf', optional: true + belongs_to :default_shelf, class_name: "Shelf", optional: true has_many :resource_import_results, dependent: :destroy has_many :resource_import_file_transitions, autosave: false, dependent: :destroy @@ -26,13 +26,13 @@ def state_machine def import_start case edit_mode - when 'create' + when "create" import - when 'update' + when "update" modify - when 'destroy' + when "destroy" remove - when 'update_relationship' + when "update_relationship" update_relationship else import @@ -50,84 +50,84 @@ def import } rows = open_import_file(create_import_temp_file(attachment)) rows.shift - #if [field['manifestation_id'], field['manifestation_identifier'], field['isbn'], field['original_title']].reject{|f| + # if [field['manifestation_id'], field['manifestation_identifier'], field['isbn'], field['original_title']].reject{|f| # f.to_s.strip == '' - #}.empty? + # }.empty? # raise "You should specify isbn or original_title in the first line" - #end + # end row_num = 1 - ResourceImportResult.create!(resource_import_file_id: id, body: (%w( imported_manifestation_id imported_item_id ) + rows.headers).join("\t")) + ResourceImportResult.create!(resource_import_file_id: id, body: (%w[ imported_manifestation_id imported_item_id ] + rows.headers).join("\t")) rows.each do |row| row_num += 1 import_result = ResourceImportResult.new(resource_import_file_id: id) - if row['dummy'].to_s.strip.present? + if row["dummy"].to_s.strip.present? import_result.error_message = "line #{row_num}: #{I18n.t('import.dummy')}" - import_result.body = ([nil, nil] + row.fields).join("\t") + import_result.body = ([ nil, nil ] + row.fields).join("\t") import_result.save! next end - item_identifier = row['item_identifier'].to_s.strip + item_identifier = row["item_identifier"].to_s.strip item = Item.find_by(item_identifier: item_identifier) if item import_result.item = item import_result.manifestation = item.manifestation import_result.error_message = "line #{row_num}: #{I18n.t('import.item_found')}" - import_result.body = ([item.manifestation.id, item.id] + row.fields).join("\t") + import_result.body = ([ item.manifestation.id, item.id ] + row.fields).join("\t") import_result.save! num[:item_found] += 1 next end - if row['manifestation_identifier'].present? - manifestation = Manifestation.find_by(manifestation_identifier: row['manifestation_identifier'].to_s.strip) + if row["manifestation_identifier"].present? + manifestation = Manifestation.find_by(manifestation_identifier: row["manifestation_identifier"].to_s.strip) end unless manifestation - if row['manifestation_id'].present? - manifestation = Manifestation.find_by(id: row['manifestation_id'].to_s.strip) + if row["manifestation_id"].present? + manifestation = Manifestation.find_by(id: row["manifestation_id"].to_s.strip) end end unless manifestation - if row['iss_itemno'].present? - iss_itemno = URI.parse(row['iss_itemno']).path.gsub(/^\//, "") + if row["iss_itemno"].present? + iss_itemno = URI.parse(row["iss_itemno"]).path.gsub(/^\//, "") manifestation = NdlBibIdRecord.find_by(body: iss_itemno).manifestation end end unless manifestation - if row['doi'].present? - doi = URI.parse(row['doi'].downcase).path.gsub(/^\//, "") + if row["doi"].present? + doi = URI.parse(row["doi"].downcase).path.gsub(/^\//, "") manifestation = DoiRecord.find_by(body: doi)&.manifestation end end unless manifestation - if row['jpno'].present? - jpno = row['jpno'].to_s.strip + if row["jpno"].present? + jpno = row["jpno"].to_s.strip manifestation = JpnoRecord.find_by(body: jpno)&.manifestation end end unless manifestation - if row['ncid'].present? - ncid = row['ncid'].to_s.strip + if row["ncid"].present? + ncid = row["ncid"].to_s.strip manifestation = NcidRecord.find_by(body: ncid)&.manifestation end end unless manifestation - if row['lccn'].present? - lccn = row['lccn'].to_s.strip + if row["lccn"].present? + lccn = row["lccn"].to_s.strip manifestation = LccnRecord.find_by(body: lccn).manifestation end end unless manifestation - if row['isbn'].present? - row['isbn'].to_s.split("//").each do |isbn| + if row["isbn"].present? + row["isbn"].to_s.split("//").each do |isbn| m = IsbnRecord.find_by(body: Lisbn.new(isbn).isbn13)&.manifestations&.first if m if m.series_statements.exists? @@ -145,18 +145,18 @@ def import num[:manifestation_found] += 1 end - if row['original_title'].blank? + if row["original_title"].blank? unless manifestation begin - if row['jpno'].present? - manifestation = Manifestation.import_from_ndl_search(jpno: row['jpno']) + if row["jpno"].present? + manifestation = Manifestation.import_from_ndl_search(jpno: row["jpno"]) end - if row['ncid'].present? - manifestation = Manifestation.import_from_cinii_books(ncid: row['ncid']) + if row["ncid"].present? + manifestation = Manifestation.import_from_cinii_books(ncid: row["ncid"]) end - row['isbn'].to_s.split("//").each do |isbn| + row["isbn"].to_s.split("//").each do |isbn| lisbn = Lisbn.new(isbn) manifestation = Manifestation.import_from_ndl_search(isbn: lisbn.isbn13) if lisbn.isbn13 end @@ -172,8 +172,8 @@ def import import_result.error_message = "line #{row_num}: #{I18n.t('import.isbn_record_not_found')}" end end - if manifestation.nil? && row['ndl_bib_id'] - manifestation = Manifestation.import_ndl_bib_id(row['ndl_bib_id']) + if manifestation.nil? && row["ndl_bib_id"] + manifestation = Manifestation.import_ndl_bib_id("R100000002-I#{row['ndl_bib_id']}") if manifestation num[:manifestation_imported] += 1 end @@ -192,14 +192,14 @@ def import end item = nil - if item_identifier.present? || row['shelf'].present? || row['call_number'].present? + if item_identifier.present? || row["shelf"].present? || row["call_number"].present? item = create_item(row, manifestation) else if manifestation.fulltext_content? item = create_item(row, manifestation) - item.circulation_status = CirculationStatus.find_by(name: 'Available On Shelf') + item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf") begin - item.acquired_at = Time.zone.parse(row['acquired_at'].to_s.strip) + item.acquired_at = Time.zone.parse(row["acquired_at"].to_s.strip) rescue ArgumentError end end @@ -217,7 +217,7 @@ def import num[:failed] += 1 end - import_result.body = ([manifestation.try(:id), item.try(:id)] + row.fields).join("\t") + import_result.body = ([ manifestation.try(:id), item.try(:id) ] + row.fields).join("\t") import_result.save! num[:item_imported] += 1 if import_result.item end @@ -238,21 +238,21 @@ def import raise e end - def self.import_work(title, agents, options = {edit_mode: 'create'}) + def self.import_work(title, agents, options = { edit_mode: "create" }) work = Manifestation.new(title) work.save work.creators = agents.uniq unless agents.empty? work end - def self.import_expression(work, agents, options = {edit_mode: 'create'}) + def self.import_expression(work, agents, options = { edit_mode: "create" }) expression = work expression.save expression.contributors = agents.uniq unless agents.empty? expression end - def self.import_manifestation(expression, agents, options = {}, edit_options = {edit_mode: 'create'}) + def self.import_manifestation(expression, agents, options = {}, edit_options = { edit_mode: "create" }) manifestation = expression manifestation.during_import = true manifestation.reload @@ -265,18 +265,18 @@ def self.import_manifestation(expression, agents, options = {}, edit_options = { def import_marc(marc_type) file = attachment.download case marc_type - when 'marcxml' + when "marcxml" reader = MARC::XMLReader.new(file) else reader = MARC::Reader.new(file) end file.close - #when 'marc_xml_url' + # when 'marc_xml_url' # url = URI(params[:marc_xml_url]) # xml = open(url).read # reader = MARC::XMLReader.new(StringIO.new(xml)) - #end + # end # TODO reader.each do |record| @@ -286,8 +286,8 @@ def import_marc(marc_type) manifestation.language = Language.find(1) manifestation.save - full_name = record['700']['a'] - publisher = Agent.find_by(full_name: record['700']['a']) + full_name = record["700"]["a"] + publisher = Agent.find_by(full_name: record["700"]["a"]) unless publisher publisher = Agent.new(full_name: full_name) publisher.save @@ -304,11 +304,11 @@ def self.import Rails.logger.info "#{Time.zone.now} importing resources failed!" end - #def import_jpmarc + # def import_jpmarc # marc = NKF::nkf('-wc', self.db_file.data) # marc.split("\r\n").each do |record| # end - #end + # end def modify transition_to!(:started) @@ -320,14 +320,14 @@ def modify rows.each do |row| row_num += 1 import_result = ResourceImportResult.create!(resource_import_file_id: id, body: row.fields.join("\t")) - item = Item.find_by(item_identifier: row['item_identifier'].to_s.strip) if row['item_identifier'].to_s.strip.present? + item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present? unless item - item = Item.find_by(id: row['item_id'].to_s.strip) if row['item_id'].to_s.strip.present? + item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present? end if item if item.manifestation - fetch(row, edit_mode: 'update') + fetch(row, edit_mode: "update") item = update_item(item, row) end @@ -342,11 +342,11 @@ def modify item.save! import_result.item = item else - manifestation_identifier = row['manifestation_identifier'].to_s.strip + manifestation_identifier = row["manifestation_identifier"].to_s.strip manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier) if manifestation_identifier.present? - manifestation ||= Manifestation.find_by(id: row['manifestation_id']) + manifestation ||= Manifestation.find_by(id: row["manifestation_id"]) if manifestation - fetch(row, edit_mode: 'update') + fetch(row, edit_mode: "update") ResourceImportFile.import_manifestation_custom_value(row, manifestation).each do |value| value.update!(manifestation: manifestation) end @@ -375,9 +375,9 @@ def remove rows.each do |row| row_num += 1 - item = Item.find_by(item_identifier: row['item_identifier'].to_s.strip) if row['item_identifier'].to_s.strip.present? + item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present? unless item - item = Item.find_by(id: row['item_id'].to_s.strip) if row['item_id'].to_s.strip.present? + item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present? end if item @@ -403,14 +403,14 @@ def update_relationship row_num = 1 rows.each do |row| - item = Item.find_by(item_identifier: row['item_identifier'].to_s.strip) if row['item_identifier'].to_s.strip.present? + item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present? unless item - item = Item.find_by(id: row['item_id'].to_s.strip) if row['item_id'].to_s.strip.present? + item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present? end - manifestation_identifier = row['manifestation_identifier'].to_s.strip + manifestation_identifier = row["manifestation_identifier"].to_s.strip manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier) - manifestation ||= Manifestation.find_by(id: row['manifestation_id'].to_s.strip) + manifestation ||= Manifestation.find_by(id: row["manifestation_id"].to_s.strip) if item && manifestation item.manifestation = manifestation @@ -439,7 +439,7 @@ def update_relationship def open_import_file(tempfile) file = CSV.open(tempfile, col_sep: "\t") - header_columns = %w( + header_columns = %w[ original_title manifestation_identifier item_identifier shelf note title_transcription title_alternative title_alternative_transcription serial manifestation_id publication_place carrier_type @@ -462,22 +462,22 @@ def open_import_file(tempfile) use_restriction include_supplements item_note item_url item_memo item_required_role dummy - ) - header_columns += ManifestationCustomProperty.order(:position).pluck(:name).map{|c| "manifestation:#{c}"} - header_columns += ItemCustomProperty.order(:position).pluck(:name).map{|c| "item:#{c}"} + ] + header_columns += ManifestationCustomProperty.order(:position).pluck(:name).map { |c| "manifestation:#{c}" } + header_columns += ItemCustomProperty.order(:position).pluck(:name).map { |c| "item:#{c}" } if defined?(EnjuSubject) - header_columns += ClassificationType.order(:position).pluck(:name).map{|c| "classification:#{c}"} - header_columns += SubjectHeadingType.order(:position).pluck(:name).map{|s| "subject:#{s}"} + header_columns += ClassificationType.order(:position).pluck(:name).map { |c| "classification:#{c}" } + header_columns += SubjectHeadingType.order(:position).pluck(:name).map { |s| "subject:#{s}" } end header = file.first ignored_columns = header - header_columns unless ignored_columns.empty? - self.error_message = I18n.t('import.following_column_were_ignored', column: ignored_columns.join(', ')) + self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", ")) save! end rows = CSV.open(tempfile, headers: header, col_sep: "\t") - #ResourceImportResult.create!(resource_import_file_id: id, body: header.join("\t")) + # ResourceImportResult.create!(resource_import_file_id: id, body: header.join("\t")) tempfile.close(true) file.close rows @@ -485,17 +485,17 @@ def open_import_file(tempfile) def import_subject(row) subjects = [] - SubjectHeadingType.order(:position).pluck(:name).map{|s| "subject:#{s}"}.each do |column_name| - type = column_name.split(':').last - subject_list = row[column_name].to_s.split('//') - subject_list.map{|value| + SubjectHeadingType.order(:position).pluck(:name).map { |s| "subject:#{s}" }.each do |column_name| + type = column_name.split(":").last + subject_list = row[column_name].to_s.split("//") + subject_list.map { |value| subject_heading_type = SubjectHeadingType.find_by(name: type) next unless subject_heading_type subject = Subject.new(term: value) subject.subject_heading_type = subject_heading_type # TODO: Subject typeの設定 - subject.subject_type = SubjectType.find_by(name: 'concept') + subject.subject_type = SubjectType.find_by(name: "concept") subject.save! subjects << subject } @@ -505,10 +505,10 @@ def import_subject(row) def import_classification(row) classifications = [] - ClassificationType.order(:position).pluck(:name).map{|c| "classification:#{c}"}.each do |column_name| - type = column_name.split(':').last - classification_list = row[column_name].to_s.split('//') - classification_list.map{|value| + ClassificationType.order(:position).pluck(:name).map { |c| "classification:#{c}" }.each do |column_name| + type = column_name.split(":").last + classification_list = row[column_name].to_s.split("//") + classification_list.map { |value| classification_type = ClassificationType.find_by(name: type) next unless classification_type @@ -522,31 +522,31 @@ def import_classification(row) end def create_item(row, manifestation) - shelf = Shelf.find_by(name: row['shelf'].to_s.strip) + shelf = Shelf.find_by(name: row["shelf"].to_s.strip) shelf ||= default_shelf || Shelf.web - bookstore = Bookstore.find_by(name: row['bookstore'].to_s.strip) - budget_type = BudgetType.find_by(name: row['budget_type'].to_s.strip) - acquired_at = Time.zone.parse(row['acquired_at']) rescue nil - binded_at = Time.zone.parse(row['binded_at']) rescue nil + bookstore = Bookstore.find_by(name: row["bookstore"].to_s.strip) + budget_type = BudgetType.find_by(name: row["budget_type"].to_s.strip) + acquired_at = Time.zone.parse(row["acquired_at"]) rescue nil + binded_at = Time.zone.parse(row["binded_at"]) rescue nil item = Item.new( manifestation_id: manifestation.id, - item_identifier: row['item_identifier'], - price: row['item_price'], - call_number: row['call_number'].to_s.strip, + item_identifier: row["item_identifier"], + price: row["item_price"], + call_number: row["call_number"].to_s.strip, acquired_at: acquired_at, - binding_item_identifier: row['binding_item_identifier'], - binding_call_number: row['binding_call_number'], + binding_item_identifier: row["binding_item_identifier"], + binding_call_number: row["binding_call_number"], binded_at: binded_at, - url: row['item_url'], - note: row['item_note'].try(:gsub, /\\n/, "\n"), - memo: row['item_memo'].try(:gsub, /\\n/, "\n") + url: row["item_url"], + note: row["item_note"].try(:gsub, /\\n/, "\n"), + memo: row["item_memo"].try(:gsub, /\\n/, "\n") ) manifestation.items << item if defined?(EnjuCirculation) - circulation_status = CirculationStatus.find_by(name: row['circulation_status'].to_s.strip) || CirculationStatus.find_by(name: 'In Process') + circulation_status = CirculationStatus.find_by(name: row["circulation_status"].to_s.strip) || CirculationStatus.find_by(name: "In Process") item.circulation_status = circulation_status - use_restriction = UseRestriction.find_by(name: row['use_restriction'].to_s.strip) - use_restriction ||= UseRestriction.find_by(name: 'Not For Loan') + use_restriction = UseRestriction.find_by(name: row["use_restriction"].to_s.strip) + use_restriction ||= UseRestriction.find_by(name: "Not For Loan") item.use_restriction = use_restriction end item.bookstore = bookstore @@ -554,7 +554,7 @@ def create_item(row, manifestation) item.shelf = shelf item.shelf = Shelf.web unless item.shelf - if %w(t true).include?(row['include_supplements'].to_s.downcase.strip) + if %w[t true].include?(row["include_supplements"].to_s.downcase.strip) item.include_supplements = true end item.save! @@ -562,45 +562,45 @@ def create_item(row, manifestation) end def update_item(item, row) - shelf = Shelf.find_by(name: row['shelf'].to_s.strip) - bookstore = Bookstore.find_by(name: row['bookstore']) - required_role = Role.find_by(name: row['item_required_role']) + shelf = Shelf.find_by(name: row["shelf"].to_s.strip) + bookstore = Bookstore.find_by(name: row["bookstore"]) + required_role = Role.find_by(name: row["item_required_role"]) item.shelf = shelf if shelf item.bookstore = bookstore if bookstore item.required_role = required_role if required_role - acquired_at = Time.zone.parse(row['acquired_at']) rescue nil - binded_at = Time.zone.parse(row['binded_at']) rescue nil + acquired_at = Time.zone.parse(row["acquired_at"]) rescue nil + binded_at = Time.zone.parse(row["binded_at"]) rescue nil item.acquired_at = acquired_at if acquired_at item.binded_at = binded_at if binded_at if defined?(EnjuCirculation) - circulation_status = CirculationStatus.find_by(name: row['circulation_status']) - checkout_type = CheckoutType.find_by(name: row['checkout_type']) - use_restriction = UseRestriction.find_by(name: row['use_restriction'].to_s.strip) + circulation_status = CirculationStatus.find_by(name: row["circulation_status"]) + checkout_type = CheckoutType.find_by(name: row["checkout_type"]) + use_restriction = UseRestriction.find_by(name: row["use_restriction"].to_s.strip) item.circulation_status = circulation_status if circulation_status item.checkout_type = checkout_type if checkout_type item.use_restriction = use_restriction if use_restriction end - item_columns = %w( + item_columns = %w[ call_number binding_item_identifier binding_call_number binded_at - ) + ] item_columns.each do |column| if row[column].present? item.assign_attributes(:"#{column}" => row[column]) end end - item.price = row['item_price'] if row['item_price'].present? - item.note = row['item_note'].try(:gsub, /\\n/, "\n") if row['item_note'].present? - item.memo = row['item_memo'].try(:gsub, /\\n/, "\n") if row['item_memo'].present? - item.url = row['item_url'] if row['item_url'].present? + item.price = row["item_price"] if row["item_price"].present? + item.note = row["item_note"].try(:gsub, /\\n/, "\n") if row["item_note"].present? + item.memo = row["item_memo"].try(:gsub, /\\n/, "\n") if row["item_memo"].present? + item.url = row["item_url"] if row["item_url"].present? - if row['include_supplements'] - if %w(t true).include?(row['include_supplements'].downcase.strip) + if row["include_supplements"] + if %w[t true].include?(row["include_supplements"].downcase.strip) item.include_supplements = true elsif item.include_supplements item.include_supplements = false @@ -610,81 +610,81 @@ def update_item(item, row) item end - def fetch(row, options = {edit_mode: 'create'}) + def fetch(row, options = { edit_mode: "create" }) manifestation = nil item = nil - if options[:edit_mode] == 'update' - if row['item_identifier'].to_s.strip.present? - item = Item.find_by(item_identifier: row['item_identifier'].to_s.strip) + if options[:edit_mode] == "update" + if row["item_identifier"].to_s.strip.present? + item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) end - if row['item_id'].to_s.strip.present? - item = Item.find_by(id: row['item_id'].to_s.strip) + if row["item_id"].to_s.strip.present? + item = Item.find_by(id: row["item_id"].to_s.strip) end manifestation = item.manifestation if item unless manifestation - manifestation_identifier = row['manifestation_identifier'].to_s.strip + manifestation_identifier = row["manifestation_identifier"].to_s.strip manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier) if manifestation_identifier - manifestation ||= Manifestation.find_by(id: row['manifestation_id']) + manifestation ||= Manifestation.find_by(id: row["manifestation_id"]) end end title = {} - title[:original_title] = row['original_title'].to_s.strip - title[:title_transcription] = row['title_transcription'].to_s.strip - title[:title_alternative] = row['title_alternative'].to_s.strip - title[:title_alternative_transcription] = row['title_alternative_transcription'].to_s.strip - if options[:edit_mode] == 'update' - title[:original_title] = manifestation.original_title if row['original_title'].to_s.strip.blank? - title[:title_transcription] = manifestation.title_transcription if row['title_transcription'].to_s.strip.blank? - title[:title_alternative] = manifestation.title_alternative if row['title_alternative'].to_s.strip.blank? - title[:title_alternative_transcription] = manifestation.title_alternative_transcription if row['title_alternative_transcription'].to_s.strip.blank? + title[:original_title] = row["original_title"].to_s.strip + title[:title_transcription] = row["title_transcription"].to_s.strip + title[:title_alternative] = row["title_alternative"].to_s.strip + title[:title_alternative_transcription] = row["title_alternative_transcription"].to_s.strip + if options[:edit_mode] == "update" + title[:original_title] = manifestation.original_title if row["original_title"].to_s.strip.blank? + title[:title_transcription] = manifestation.title_transcription if row["title_transcription"].to_s.strip.blank? + title[:title_alternative] = manifestation.title_alternative if row["title_alternative"].to_s.strip.blank? + title[:title_alternative_transcription] = manifestation.title_alternative_transcription if row["title_alternative_transcription"].to_s.strip.blank? end - #title[:title_transcription_alternative] = row['title_transcription_alternative'] - if title[:original_title].blank? && options[:edit_mode] == 'create' + # title[:title_transcription_alternative] = row['title_transcription_alternative'] + if title[:original_title].blank? && options[:edit_mode] == "create" return nil end # TODO: 小数点以下の表現 - language = Language.find_by(name: row['language'].to_s.strip.camelize) || Language.find_by(iso_639_2: row['language'].to_s.strip.downcase) || Language.find_by(iso_639_1: row['language'].to_s.strip.downcase) + language = Language.find_by(name: row["language"].to_s.strip.camelize) || Language.find_by(iso_639_2: row["language"].to_s.strip.downcase) || Language.find_by(iso_639_1: row["language"].to_s.strip.downcase) - carrier_type = CarrierType.find_by(name: row['carrier_type'].to_s.strip) - content_type = ContentType.find_by(name: row['content_type'].to_s.strip) - frequency = Frequency.find_by(name: row['frequency'].to_s.strip) + carrier_type = CarrierType.find_by(name: row["carrier_type"].to_s.strip) + content_type = ContentType.find_by(name: row["content_type"].to_s.strip) + frequency = Frequency.find_by(name: row["frequency"].to_s.strip) fulltext_content = serial = nil - if %w(t true).include?(row['fulltext_content'].to_s.downcase.strip) + if %w[t true].include?(row["fulltext_content"].to_s.downcase.strip) fulltext_content = true end - if %w(t true).include?(row['serial'].to_s.downcase.strip) + if %w[t true].include?(row["serial"].to_s.downcase.strip) serial = true end - creators = row['creator'].to_s.split('//') - creator_transcriptions = row['creator_transcription'].to_s.split('//') - creators_list = creators.zip(creator_transcriptions).map{|f, t| {full_name: f.to_s.strip, full_name_transcription: t.to_s.strip}} - contributors = row['contributor'].to_s.split('//') - contributor_transcriptions = row['contributor_transcription'].to_s.split('//') - contributors_list = contributors.zip(contributor_transcriptions).map{|f, t| {full_name: f.to_s.strip, full_name_transcription: t.to_s.strip}} - publishers = row['publisher'].to_s.split('//') - publisher_transcriptions = row['publisher_transcription'].to_s.split('//') - publishers_list = publishers.zip(publisher_transcriptions).map{|f, t| {full_name: f.to_s.strip, full_name_transcription: t.to_s.strip}} + creators = row["creator"].to_s.split("//") + creator_transcriptions = row["creator_transcription"].to_s.split("//") + creators_list = creators.zip(creator_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } } + contributors = row["contributor"].to_s.split("//") + contributor_transcriptions = row["contributor_transcription"].to_s.split("//") + contributors_list = contributors.zip(contributor_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } } + publishers = row["publisher"].to_s.split("//") + publisher_transcriptions = row["publisher_transcription"].to_s.split("//") + publishers_list = publishers.zip(publisher_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } } ResourceImportFile.transaction do creator_agents = Agent.import_agents(creators_list) contributor_agents = Agent.import_agents(contributors_list) publisher_agents = Agent.import_agents(publishers_list) subjects = import_subject(row) if defined?(EnjuSubject) case options[:edit_mode] - when 'create' + when "create" work = self.class.import_work(title, creator_agents, options) if defined?(EnjuSubject) work.subjects = subjects.uniq unless subjects.empty? end expression = self.class.import_expression(work, contributor_agents) - when 'update' + when "update" expression = manifestation work = expression work.creators = creator_agents.uniq unless creator_agents.empty? @@ -699,74 +699,74 @@ def fetch(row, options = {edit_mode: 'create'}) title_transcription: title[:title_transcription], title_alternative: title[:title_alternative], title_alternative_transcription: title[:title_alternative_transcription], - pub_date: row['pub_date'], - date_of_publication: row['date_of_publication'], - year_of_publication: row['year_of_publication'], - volume_number: row['volume_number'], - volume_number_string: row['volume_number_string'], - issue_number: row['issue_number'], - issue_number_string: row['issue_number_string'], - serial_number: row['serial_number'], - edition: row['edition'], - edition_string: row['edition_string'], - width: row['width'], - depth: row['depth'], - height: row['height'], - price: row['manifestation_price'], - abstract: row['abstract'].try(:gsub, /\\n/, "\n"), - description: row['description'].try(:gsub, /\\n/, "\n"), - #:description_transcription => row['description_transcription'], - note: row['note'].try(:gsub, /\\n/, "\n"), - memo: row['manifestation_memo'].try(:gsub, /\\n/, "\n"), - statement_of_responsibility: row['statement_of_responsibility'], - access_address: row['access_address'], - manifestation_identifier: row['manifestation_identifier'], - publication_place: row['publication_place'], - extent: row['extent'], - dimensions: row['dimensions'], - start_page: row['start_page'], - end_page: row['end_page'], - }.delete_if{|_key, value| value.nil?} + pub_date: row["pub_date"], + date_of_publication: row["date_of_publication"], + year_of_publication: row["year_of_publication"], + volume_number: row["volume_number"], + volume_number_string: row["volume_number_string"], + issue_number: row["issue_number"], + issue_number_string: row["issue_number_string"], + serial_number: row["serial_number"], + edition: row["edition"], + edition_string: row["edition_string"], + width: row["width"], + depth: row["depth"], + height: row["height"], + price: row["manifestation_price"], + abstract: row["abstract"].try(:gsub, /\\n/, "\n"), + description: row["description"].try(:gsub, /\\n/, "\n"), + # :description_transcription => row['description_transcription'], + note: row["note"].try(:gsub, /\\n/, "\n"), + memo: row["manifestation_memo"].try(:gsub, /\\n/, "\n"), + statement_of_responsibility: row["statement_of_responsibility"], + access_address: row["access_address"], + manifestation_identifier: row["manifestation_identifier"], + publication_place: row["publication_place"], + extent: row["extent"], + dimensions: row["dimensions"], + start_page: row["start_page"], + end_page: row["end_page"], + }.delete_if { |_key, value| value.nil? } manifestation = self.class.import_manifestation(expression, publisher_agents, attributes, { edit_mode: options[:edit_mode] }) - required_role = Role.find_by(name: row['manifestation_required_role'].to_s.strip.camelize) - if required_role && row['manifestation_required_role'].present? + required_role = Role.find_by(name: row["manifestation_required_role"].to_s.strip.camelize) + if required_role && row["manifestation_required_role"].present? manifestation.required_role = required_role else - manifestation.required_role = Role.find_by(name: 'Guest') unless manifestation.required_role + manifestation.required_role = Role.find_by(name: "Guest") unless manifestation.required_role end - if language && row['language'].present? + if language && row["language"].present? manifestation.language = language else - manifestation.language = Language.find_by(name: 'unknown') unless manifestation.language + manifestation.language = Language.find_by(name: "unknown") unless manifestation.language end manifestation.carrier_type = carrier_type if carrier_type manifestation.manifestation_content_type = content_type if content_type manifestation.frequency = frequency if frequency - #manifestation.start_page = row[:start_page].to_i if row[:start_page] - #manifestation.end_page = row[:end_page].to_i if row[:end_page] - manifestation.serial = serial if row['serial'] - manifestation.fulltext_content = fulltext_content if row['fulltext_content'] + # manifestation.start_page = row[:start_page].to_i if row[:start_page] + # manifestation.end_page = row[:end_page].to_i if row[:end_page] + manifestation.serial = serial if row["serial"] + manifestation.fulltext_content = fulltext_content if row["fulltext_content"] - if row['series_original_title'].to_s.strip.present? + if row["series_original_title"].to_s.strip.present? Manifestation.transaction do if manifestation.series_statements.exists? manifestation.series_statements.delete_all end - if row['series_original_title'] + if row["series_original_title"] series_statement = SeriesStatement.new( - original_title: row['series_original_title'], - title_transcription: row['series_title_transcription'], - title_subseries: row['series_title_subseries'], - title_subseries_transcription: row['series_title_subseries_transcription'], - volume_number_string: row['series_volume_number_string'], - creator_string: row['series_creator_string'] + original_title: row["series_original_title"], + title_transcription: row["series_title_transcription"], + title_subseries: row["series_title_subseries"], + title_subseries_transcription: row["series_title_subseries_transcription"], + volume_number_string: row["series_volume_number_string"], + creator_string: row["series_creator_string"] ) series_statement.manifestation = manifestation series_statement.save! @@ -775,17 +775,17 @@ def fetch(row, options = {edit_mode: 'create'}) end manifestation.doi_record = set_doi(row) - manifestation.create_jpno_record(body: row['jpno']) if row['jpno'].present? - manifestation.create_ncid_record(body: row['ncid']) if row['ncid'].present? - if row['isbn'].present? - row['isbn'].to_s.split("//").each do |isbn| + manifestation.create_jpno_record(body: row["jpno"]) if row["jpno"].present? + manifestation.create_ncid_record(body: row["ncid"]) if row["ncid"].present? + if row["isbn"].present? + row["isbn"].to_s.split("//").each do |isbn| lisbn = Lisbn.new(isbn) manifestation.isbn_records.find_or_create_by(body: lisbn.isbn13) if lisbn.isbn13 end end - if row['issn'].present? - row['issn'].to_s.split("//").each do |issn| + if row["issn"].present? + row["issn"].to_s.split("//").each do |issn| manifestation.issn_records.find_or_create_by(body: issn) if issn.present? end end @@ -794,7 +794,7 @@ def fetch(row, options = {edit_mode: 'create'}) if manifestation.save Manifestation.transaction do - if options[:edit_mode] == 'update' + if options[:edit_mode] == "update" unless identifiers.empty? identifiers.each do |v| v.manifestation = manifestation @@ -816,7 +816,7 @@ def fetch(row, options = {edit_mode: 'create'}) manifestation.save! - if options[:edit_mode] == 'create' + if options[:edit_mode] == "create" manifestation.set_agent_role_type(creators_list) manifestation.set_agent_role_type(contributors_list, scope: :contributor) manifestation.set_agent_role_type(publishers_list, scope: :publisher) @@ -828,7 +828,7 @@ def fetch(row, options = {edit_mode: 'create'}) def set_identifier(row) identifiers = [] - %w(isbn issn jpno ncid lccn iss_itemno).each do |id_type| + %w[isbn issn jpno ncid lccn iss_itemno].each do |id_type| next unless row[id_type.to_s].present? row[id_type].split(/\/\//).each do |identifier_s| @@ -843,9 +843,9 @@ def set_identifier(row) end def set_doi(row) - return if row['doi'].blank? + return if row["doi"].blank? - doi = URI.parse(row['doi'].downcase).path.gsub(/^\//, "") + doi = URI.parse(row["doi"].downcase).path.gsub(/^\//, "") doi_record = DoiRecord.new(body: doi) doi_record @@ -853,9 +853,9 @@ def set_doi(row) def self.import_manifestation_custom_value(row, manifestation) values = [] - ManifestationCustomProperty.order(:position).pluck(:name).map{|c| "manifestation:#{c}"}.each do |column_name| + ManifestationCustomProperty.order(:position).pluck(:name).map { |c| "manifestation:#{c}" }.each do |column_name| value = nil - property = column_name.split(':').last + property = column_name.split(":").last next if row[column_name].blank? if manifestation @@ -877,9 +877,9 @@ def self.import_manifestation_custom_value(row, manifestation) def self.import_item_custom_value(row, item) values = [] - ItemCustomProperty.order(:position).pluck(:name).map{|c| "item:#{c}"}.each do |column_name| + ItemCustomProperty.order(:position).pluck(:name).map { |c| "item:#{c}" }.each do |column_name| value = nil - property = column_name.split(':').last + property = column_name.split(":").last next if row[column_name].blank? value = item.item_custom_values.find_by(item_custom_property: property) if item diff --git a/app/models/resource_import_file_state_machine.rb b/app/models/resource_import_file_state_machine.rb index 335579ff7f..54b472c6c0 100644 --- a/app/models/resource_import_file_state_machine.rb +++ b/app/models/resource_import_file_state_machine.rb @@ -6,8 +6,8 @@ class ResourceImportFileStateMachine state :completed state :failed - transition from: :pending, to: [:started, :failed] - transition from: :started, to: [:completed, :failed] + transition from: :pending, to: [ :started, :failed ] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |resource_import_file| resource_import_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/resource_import_file_transition.rb b/app/models/resource_import_file_transition.rb index 4d27a9fe6f..daa5349940 100644 --- a/app/models/resource_import_file_transition.rb +++ b/app/models/resource_import_file_transition.rb @@ -1,7 +1,4 @@ class ResourceImportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :resource_import_file, inverse_of: :resource_import_file_transitions end @@ -11,7 +8,7 @@ class ResourceImportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # resource_import_file_id :bigint # created_at :datetime not null diff --git a/app/models/resource_import_result.rb b/app/models/resource_import_result.rb index d8e1b9a82d..33573549cc 100644 --- a/app/models/resource_import_result.rb +++ b/app/models/resource_import_result.rb @@ -1,6 +1,6 @@ class ResourceImportResult < ApplicationRecord - default_scope { order('resource_import_results.id') } - scope :file_id, proc{|file_id| where(resource_import_file_id: file_id)} + default_scope { order("resource_import_results.id") } + scope :file_id, proc { |file_id| where(resource_import_file_id: file_id) } scope :failed, -> { where(manifestation_id: nil) } scope :skipped, -> { where.not(error_message: nil) } diff --git a/app/models/resourcesync.rb b/app/models/resourcesync.rb index 52ef67ee2e..7113963794 100644 --- a/app/models/resourcesync.rb +++ b/app/models/resourcesync.rb @@ -1,18 +1,18 @@ class Resourcesync def initialize - @base_url = if ENV['ENJU_LEAF_RESOURCESYNC_BASE_URL'].present? - URI.parse(ENV['ENJU_LEAF_RESOURCESYNC_BASE_URL']).to_s + @base_url = if ENV["ENJU_LEAF_RESOURCESYNC_BASE_URL"].present? + URI.parse(ENV["ENJU_LEAF_RESOURCESYNC_BASE_URL"]).to_s else - URI.parse(ENV['ENJU_LEAF_BASE_URL']).to_s + URI.parse(ENV["ENJU_LEAF_BASE_URL"]).to_s end end def generate_capabilitylist capabilitylist = Resync::CapabilityList.new( - links: [Resync::Link.new(rel: 'up', uri: @base_url)], + links: [ Resync::Link.new(rel: "up", uri: @base_url) ], resources: [ - Resync::Resource.new(uri: "#{@base_url}/resourcelist.xml", metadata: Resync::Metadata.new(capability: 'resourcelist')), - Resync::Resource.new(uri: "#{@base_url}/changelist.xml", metadata: Resync::Metadata.new(capability: 'changelist')) + Resync::Resource.new(uri: "#{@base_url}/resourcelist.xml", metadata: Resync::Metadata.new(capability: "resourcelist")), + Resync::Resource.new(uri: "#{@base_url}/changelist.xml", metadata: Resync::Metadata.new(capability: "changelist")) ] ) @@ -23,9 +23,9 @@ def generate_resourcelist_index(manifestations) last_updated = manifestations.order(:updated_at).first&.updated_at resourcelist_index = Resync::ResourceListIndex.new( - links: [Resync::Link.new(rel: 'up', uri: "#{@base_url}/capabilitylist.xml")], + links: [ Resync::Link.new(rel: "up", uri: "#{@base_url}/capabilitylist.xml") ], metadata: Resync::Metadata.new( - capability: 'resourcelist', + capability: "resourcelist", from_time: manifestations.order(:updated_at).pick(:updated_at) ), resources: ((manifestations.count / 50000) + 1).times.map do |i| @@ -45,12 +45,12 @@ def generate_resourcelist(manifestations) manifestations.find_in_batches(batch_size: 50000).with_index do |works, i| resourcelist = Resync::ResourceList.new( - links: [Resync::Link.new(rel: 'up', uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s)], + links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ], metadata: Resync::Metadata.new( - capability: 'resourcelist', + capability: "resourcelist", from_time: last_updated ), - resources: works.map{|m| + resources: works.map { |m| Resync::Resource.new( uri: "#{@base_url}/manifestations/#{m.id}", modified_time: m.updated_at @@ -68,9 +68,9 @@ def generate_changelist_index(manifestations) last_updated = manifestations.order(:updated_at).first&.updated_at changelist_index = Resync::ChangeListIndex.new( - links: [Resync::Link.new(rel: 'up', uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s)], + links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ], metadata: Resync::Metadata.new( - capability: 'changelist', + capability: "changelist", from_time: manifestations.order(:updated_at).pick(:updated_at) ), resources: ((manifestations.count / 50000) + 1).times.map do |i| @@ -90,12 +90,12 @@ def generate_changelist(manifestations) manifestations.find_in_batches(batch_size: 50000).with_index do |works, i| changelist = Resync::ChangeList.new( - links: [Resync::Link.new(rel: 'up', uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s)], + links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ], metadata: Resync::Metadata.new( - capability: 'changelist', + capability: "changelist", from_time: last_updated ), - resources: works.map{|m| + resources: works.map { |m| Resync::Resource.new( uri: "#{@base_url}/manifestations/#{m.id}", modified_time: m.updated_at, diff --git a/app/models/role.rb b/app/models/role.rb index 238cdc3420..edaeee3e24 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -12,7 +12,7 @@ def localized_name end def self.default - Role.find_by(name: 'Guest') + Role.find_by(name: "Guest") end private diff --git a/app/models/search_engine.rb b/app/models/search_engine.rb index 595e9d3c46..127053511d 100644 --- a/app/models/search_engine.rb +++ b/app/models/search_engine.rb @@ -3,7 +3,7 @@ class SearchEngine < ApplicationRecord validates :name, presence: true validates :query_param, presence: true - validates :http_method, presence: true, inclusion: %w(get post) + validates :http_method, presence: true, inclusion: %w[get post] validates :url, presence: true, url: true, length: { maximum: 255 } validates :base_url, presence: true, url: true, length: { maximum: 255 } @@ -12,8 +12,8 @@ class SearchEngine < ApplicationRecord def search_params(query) params = {} if additional_param - additional_param.gsub('{query}', query).to_s.split.each do |param| - p = param.split('=') + additional_param.gsub("{query}", query).to_s.split.each do |param| + p = param.split("=") params[p[0].to_sym] = p[1] end params diff --git a/app/models/series_statement.rb b/app/models/series_statement.rb index abee086c33..04d30b5317 100644 --- a/app/models/series_statement.rb +++ b/app/models/series_statement.rb @@ -2,7 +2,7 @@ class SeriesStatement < ApplicationRecord has_many :series_statement_merges, dependent: :destroy has_many :series_statement_merge_lists, through: :series_statement_merges belongs_to :manifestation, touch: true, optional: true - belongs_to :root_manifestation, class_name: 'Manifestation', touch: true, optional: true + belongs_to :root_manifestation, class_name: "Manifestation", touch: true, optional: true validates :original_title, presence: true validates :root_manifestation_id, uniqueness: true, allow_nil: true before_save :create_root_series_statement diff --git a/app/models/shelf.rb b/app/models/shelf.rb index 958d390a43..d45d62a55d 100644 --- a/app/models/shelf.rb +++ b/app/models/shelf.rb @@ -1,6 +1,6 @@ class Shelf < ApplicationRecord include MasterModel - scope :real, -> { where('library_id != 1') } + scope :real, -> { where("library_id != 1") } belongs_to :library has_many :items, dependent: :restrict_with_exception has_many :picture_files, as: :picture_attachable, dependent: :destroy @@ -19,7 +19,7 @@ class Shelf < ApplicationRecord library.name end text :name do - [name, library.name, display_name, library.display_name] + [ name, library.name, display_name, library.display_name ] end integer :position end diff --git a/app/models/subject.rb b/app/models/subject.rb index d9ff81fd69..4c0e1485c4 100644 --- a/app/models/subject.rb +++ b/app/models/subject.rb @@ -2,7 +2,7 @@ class Subject < ApplicationRecord belongs_to :manifestation, touch: true, optional: true belongs_to :subject_type belongs_to :subject_heading_type - belongs_to :required_role, class_name: 'Role' + belongs_to :required_role, class_name: "Role" validates :term, presence: true diff --git a/app/models/subject_heading_type.rb b/app/models/subject_heading_type.rb index 20e2a73795..0328db6dc2 100644 --- a/app/models/subject_heading_type.rb +++ b/app/models/subject_heading_type.rb @@ -1,7 +1,7 @@ class SubjectHeadingType < ApplicationRecord include MasterModel has_many :subjects, dependent: :destroy - validates :name, format: {with: /\A[0-9a-z][0-9a-z_\-]*[0-9a-z]\Z/} + validates :name, format: { with: /\A[0-9a-z][0-9a-z_\-]*[0-9a-z]\Z/ } end # == Schema Information diff --git a/app/models/subject_type.rb b/app/models/subject_type.rb index 63e539b27c..e3de83ecc3 100644 --- a/app/models/subject_type.rb +++ b/app/models/subject_type.rb @@ -1,7 +1,7 @@ class SubjectType < ApplicationRecord include MasterModel has_many :subjects, dependent: :restrict_with_exception - validates :name, format: {with: /\A[0-9A-Za-z][0-9a-z_\-]*[0-9a-z]\Z/} + validates :name, format: { with: /\A[0-9A-Za-z][0-9a-z_\-]*[0-9a-z]\Z/ } end # == Schema Information diff --git a/app/models/subscribe.rb b/app/models/subscribe.rb index 6741ea4b61..fca8e6d5f0 100644 --- a/app/models/subscribe.rb +++ b/app/models/subscribe.rb @@ -1,6 +1,6 @@ class Subscribe < ApplicationRecord belongs_to :subscription, counter_cache: true - belongs_to :work, class_name: 'Manifestation' + belongs_to :work, class_name: "Manifestation" validates :start_at, :end_at, presence: true validates :work_id, uniqueness: { scope: :subscription_id } diff --git a/app/models/tag.rb b/app/models/tag.rb index 5ee2576cdd..91aaf6e165 100644 --- a/app/models/tag.rb +++ b/app/models/tag.rb @@ -1,5 +1,5 @@ class Tag < ApplicationRecord - has_many :taggings, dependent: :destroy, class_name: 'ActsAsTaggableOn::Tagging' + has_many :taggings, dependent: :destroy, class_name: "ActsAsTaggableOn::Tagging" validates :name, presence: true after_destroy :save_taggings after_save :save_taggings diff --git a/app/models/url_validator.rb b/app/models/url_validator.rb index 3f2ce28a19..e8b42fb62b 100644 --- a/app/models/url_validator.rb +++ b/app/models/url_validator.rb @@ -2,7 +2,7 @@ class UrlValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if value =~ /\Ahttps?:\/\/[^\n]+\z/i url = ::Addressable::URI.parse(value) - unless ['http', 'https'].include?(url.scheme) + unless [ "http", "https" ].include?(url.scheme) record.errors.add(attribute.to_sym) end else diff --git a/app/models/use_restriction.rb b/app/models/use_restriction.rb index 491dc99370..d57cd97c73 100644 --- a/app/models/use_restriction.rb +++ b/app/models/use_restriction.rb @@ -2,7 +2,7 @@ class UseRestriction < ApplicationRecord include MasterModel validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ } - scope :available, -> {where(name: ['Not For Loan', 'Limited Circulation, Normal Loan Period'])} + scope :available, -> { where(name: [ "Not For Loan", "Limited Circulation, Normal Loan Period" ]) } has_many :item_has_use_restrictions, dependent: :destroy has_many :items, through: :item_has_use_restrictions diff --git a/app/models/user_checkout_stat.rb b/app/models/user_checkout_stat.rb index 9f8fa66968..7d99202845 100644 --- a/app/models/user_checkout_stat.rb +++ b/app/models/user_checkout_stat.rb @@ -4,8 +4,8 @@ class UserCheckoutStat < ApplicationRecord initial_state: UserCheckoutStatStateMachine.initial_state ] include CalculateStat - default_scope {order('user_checkout_stats.id DESC')} - scope :not_calculated, -> {in_state(:pending)} + default_scope { order("user_checkout_stats.id DESC") } + scope :not_calculated, -> { in_state(:pending) } has_many :checkout_stat_has_users, dependent: :destroy has_many :users, through: :checkout_stat_has_users belongs_to :user @@ -28,7 +28,7 @@ def calculate_count! daily_count = user.checkouts.completed(start_date.beginning_of_day, end_date.tomorrow.beginning_of_day).size if daily_count.positive? users << user - sql = ['UPDATE checkout_stat_has_users SET checkouts_count = ? WHERE user_checkout_stat_id = ? AND user_id = ?', daily_count, id, user.id] + sql = [ "UPDATE checkout_stat_has_users SET checkouts_count = ? WHERE user_checkout_stat_id = ? AND user_id = ?", daily_count, id, user.id ] UserCheckoutStat.connection.execute( self.class.send(:sanitize_sql_array, sql) ) diff --git a/app/models/user_checkout_stat_transition.rb b/app/models/user_checkout_stat_transition.rb index 6a6a471c6e..8c14c93404 100644 --- a/app/models/user_checkout_stat_transition.rb +++ b/app/models/user_checkout_stat_transition.rb @@ -1,7 +1,4 @@ class UserCheckoutStatTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :user_checkout_stat, inverse_of: :user_checkout_stat_transitions end @@ -11,7 +8,7 @@ class UserCheckoutStatTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # user_checkout_stat_id :bigint # created_at :datetime not null diff --git a/app/models/user_export_file.rb b/app/models/user_export_file.rb index 4c1c93435d..9d0e446543 100644 --- a/app/models/user_export_file.rb +++ b/app/models/user_export_file.rb @@ -19,11 +19,11 @@ def state_machine # エクスポートの処理を実行します。 def export! transition_to!(:started) - tempfile = Tempfile.new(['user_export_file_', '.txt']) + tempfile = Tempfile.new([ "user_export_file_", ".txt" ]) file = User.export(format: :text) tempfile.puts(file) tempfile.close - attachment.attach(io: File.new(tempfile.path, 'r'), filename: 'user_export.txt') + attachment.attach(io: File.new(tempfile.path, "r"), filename: "user_export.txt") save! transition_to!(:completed) mailer = UserExportMailer.completed(self) diff --git a/app/models/user_export_file_state_machine.rb b/app/models/user_export_file_state_machine.rb index 7a73a6348e..ca1adb1348 100644 --- a/app/models/user_export_file_state_machine.rb +++ b/app/models/user_export_file_state_machine.rb @@ -6,8 +6,8 @@ class UserExportFileStateMachine state :completed state :failed - transition from: :pending, to: [:started, :failed] - transition from: :started, to: [:completed, :failed] + transition from: :pending, to: [ :started, :failed ] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |user_export_file| user_export_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/user_export_file_transition.rb b/app/models/user_export_file_transition.rb index 10709cd934..ba528ae642 100644 --- a/app/models/user_export_file_transition.rb +++ b/app/models/user_export_file_transition.rb @@ -1,7 +1,4 @@ class UserExportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :user_export_file, inverse_of: :user_export_file_transitions end @@ -11,7 +8,7 @@ class UserExportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # user_export_file_id :bigint # created_at :datetime not null diff --git a/app/models/user_group_has_checkout_type.rb b/app/models/user_group_has_checkout_type.rb index f4d9b5eac4..9c30cea2bd 100644 --- a/app/models/user_group_has_checkout_type.rb +++ b/app/models/user_group_has_checkout_type.rb @@ -1,16 +1,16 @@ class UserGroupHasCheckoutType < ApplicationRecord - scope :available_for_item, lambda{|item| where(checkout_type_id: item.checkout_type.id)} - scope :available_for_carrier_type, lambda{|carrier_type| includes(checkout_type: :carrier_types).where('carrier_types.id' => carrier_type.id)} + scope :available_for_item, lambda { |item| where(checkout_type_id: item.checkout_type.id) } + scope :available_for_carrier_type, lambda { |carrier_type| includes(checkout_type: :carrier_types).where("carrier_types.id" => carrier_type.id) } belongs_to :user_group belongs_to :checkout_type validates :checkout_type_id, uniqueness: { scope: :user_group_id } - validates :checkout_limit, numericality: {only_integer: true, greater_than_or_equal_to: 0} - validates :checkout_period, numericality: {only_integer: true, greater_than_or_equal_to: 0} - validates :checkout_renewal_limit, numericality: {only_integer: true, greater_than_or_equal_to: 0} - validates :reservation_limit, numericality: {only_integer: true, greater_than_or_equal_to: 0} - validates :reservation_expired_period, numericality: {only_integer: true, greater_than_or_equal_to: 0} + validates :checkout_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 } + validates :checkout_period, numericality: { only_integer: true, greater_than_or_equal_to: 0 } + validates :checkout_renewal_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 } + validates :reservation_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 } + validates :reservation_expired_period, numericality: { only_integer: true, greater_than_or_equal_to: 0 } acts_as_list scope: :user_group_id diff --git a/app/models/user_import_file.rb b/app/models/user_import_file.rb index b2b4b04cbf..e7dcfd3ca6 100644 --- a/app/models/user_import_file.rb +++ b/app/models/user_import_file.rb @@ -4,14 +4,14 @@ class UserImportFile < ApplicationRecord initial_state: UserImportFileStateMachine.initial_state ] include ImportFile - default_scope {order('user_import_files.id DESC')} + default_scope { order("user_import_files.id DESC") } scope :not_imported, -> { in_state(:pending) } - scope :stucked, -> { in_state(:pending).where('user_import_files.created_at < ?', 1.hour.ago) } + scope :stucked, -> { in_state(:pending).where("user_import_files.created_at < ?", 1.hour.ago) } has_one_attached :attachment belongs_to :user - belongs_to :default_user_group, class_name: 'UserGroup' - belongs_to :default_library, class_name: 'Library' + belongs_to :default_user_group, class_name: "UserGroup" + belongs_to :default_library, class_name: "Library" has_many :user_import_results, dependent: :destroy has_many :user_import_file_transitions, autosave: false, dependent: :destroy @@ -33,7 +33,7 @@ def import row_num = 1 field = rows.first - if [field['username']].reject{ |f| f.to_s.strip == "" }.empty? + if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty? raise "username column is not found" end @@ -42,9 +42,9 @@ def import import_result = UserImportResult.create!( user_import_file_id: id, body: row.fields.join("\t") ) - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? - username = row['username'] + username = row["username"] new_user = User.find_by(username: username) if new_user import_result.user = new_user @@ -52,7 +52,7 @@ def import num[:user_found] += 1 else new_user = User.new - new_user.role = Role.find_by(name: row['role']) + new_user.role = Role.find_by(name: row["role"]) if new_user.role unless user.has_role?(new_user.role.name) num[:failed] += 1 @@ -64,8 +64,8 @@ def import new_user.username = username new_user.assign_attributes(set_user_params(row)) - if row['password'].to_s.strip.present? - new_user.password = row['password'] + if row["password"].to_s.strip.present? + new_user.password = row["password"] else new_user.password = Devise.friendly_token[0..7] end @@ -81,8 +81,8 @@ def import num[:user_imported] += 1 else error_message = "line #{row_num}: " - error_message += new_user.errors.map(&:full_message).join(' ') - error_message += profile.errors.map(&:full_message).join(' ') + error_message += new_user.errors.map(&:full_message).join(" ") + error_message += profile.errors.map(&:full_message).join(" ") import_result.error_message = error_message import_result.save num[:error] += 1 @@ -95,7 +95,7 @@ def import rows.close error_messages = user_import_results.order(:id).pluck(:error_message).compact unless error_messages.empty? - self.error_message = '' if error_message.nil? + self.error_message = "" if error_message.nil? self.error_message += "\n" self.error_message += error_messages.join("\n") end @@ -123,23 +123,23 @@ def modify row_num = 1 field = rows.first - if [field['username']].reject{|f| f.to_s.strip == ""}.empty? + if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty? raise "username column is not found" end rows.each do |row| row_num += 1 - next if row['dummy'].to_s.strip.present? + next if row["dummy"].to_s.strip.present? import_result = UserImportResult.create!( user_import_file_id: id, body: row.fields.join("\t") ) - username = row['username'] + username = row["username"] new_user = User.find_by(username: username) if new_user.try(:profile) new_user.assign_attributes(set_user_params(row)) - new_user.password = row['password'] if row['password'].to_s.strip.present? + new_user.password = row["password"] if row["password"].to_s.strip.present? new_user.profile.assign_attributes(set_profile_params(row)) Profile.transaction do if new_user.save && new_user.profile.save @@ -177,13 +177,13 @@ def remove rows = open_import_file(create_import_temp_file(attachment)) field = rows.first - if [field['username']].reject{ |f| f.to_s.strip == "" }.empty? + if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty? raise "username column is not found" end rows.each do |row| row_num += 1 - username = row['username'].to_s.strip + username = row["username"].to_s.strip remove_user = User.find_by(username: username) next unless remove_user.try(:deletable_by?, user) @@ -209,29 +209,29 @@ def remove # インポート作業用のファイルを読み込みます。 # @param [File] tempfile 作業用のファイル def open_import_file(tempfile) - file = CSV.open(tempfile.path, 'r:utf-8', col_sep: "\t") - header_columns = %w( + file = CSV.open(tempfile.path, "r:utf-8", col_sep: "\t") + header_columns = %w[ username role email password user_group user_number expired_at full_name full_name_transcription required_role locked keyword_list note locale library dummy - ) + ] if defined?(EnjuCirculation) - header_columns += %w(checkout_icalendar_token save_checkout_history) + header_columns += %w[checkout_icalendar_token save_checkout_history] end if defined?(EnjuSearchLog) - header_columns += %w(save_search_history) + header_columns += %w[save_search_history] end if defined?(EnjuBookmark) - header_columns += %w(share_bookmarks) + header_columns += %w[share_bookmarks] end header = file.first ignored_columns = header - header_columns unless ignored_columns.empty? - self.error_message = I18n.t('import.following_column_were_ignored', column: ignored_columns.join(', ')) + self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", ")) save! end - rows = CSV.open(tempfile.path, 'r:utf-8', headers: header, col_sep: "\t") + rows = CSV.open(tempfile.path, "r:utf-8", headers: header, col_sep: "\t") UserImportResult.create!(user_import_file_id: id, body: header.join("\t")) tempfile.close(true) file.close @@ -253,10 +253,10 @@ def self.import # @param [Hash] row 利用者情報のハッシュ def set_user_params(row) params = {} - params[:email] = row['email'] if row['email'].present? + params[:email] = row["email"] if row["email"].present? - if %w(t true).include?(row['locked'].to_s.downcase.strip) - params[:locked] = '1' + if %w[t true].include?(row["locked"].to_s.downcase.strip) + params[:locked] = "1" end params @@ -266,42 +266,42 @@ def set_user_params(row) # @param [Hash] row 利用者情報のハッシュ def set_profile_params(row) params = {} - user_group = UserGroup.find_by(name: row['user_group']) || default_user_group + user_group = UserGroup.find_by(name: row["user_group"]) || default_user_group params[:user_group_id] = user_group.id if user_group - required_role = Role.find_by(name: row['required_role']) || Role.find_by(name: 'Librarian') + required_role = Role.find_by(name: row["required_role"]) || Role.find_by(name: "Librarian") params[:required_role_id] = required_role.id if required_role - params[:user_number] = row['user_number'] if row['user_number'] - params[:full_name] = row['full_name'] if row['full_name'] - params[:full_name_transcription] = row['full_name_transcription'] if row['full_name_transcription'] + params[:user_number] = row["user_number"] if row["user_number"] + params[:full_name] = row["full_name"] if row["full_name"] + params[:full_name_transcription] = row["full_name_transcription"] if row["full_name_transcription"] - if row['expired_at'].present? - params[:expired_at] = Time.zone.parse(row['expired_at']).end_of_day + if row["expired_at"].present? + params[:expired_at] = Time.zone.parse(row["expired_at"]).end_of_day end - if row['keyword_list'].present? - params[:keyword_list] = row['keyword_list'].split('//').join("\n") + if row["keyword_list"].present? + params[:keyword_list] = row["keyword_list"].split("//").join("\n") end - params[:note] = row['note'] if row['note'] + params[:note] = row["note"] if row["note"] - if I18n.available_locales.include?(row['locale'].to_s.to_sym) - params[:locale] = row['locale'] + if I18n.available_locales.include?(row["locale"].to_s.to_sym) + params[:locale] = row["locale"] end - library = Library.find_by(name: row['library'].to_s.strip) || default_library || Library.web + library = Library.find_by(name: row["library"].to_s.strip) || default_library || Library.web params[:library_id] = library.id if library if defined?(EnjuCirculation) - params[:checkout_icalendar_token] = row['checkout_icalendar_token'] if row['checkout_icalendar_token'].present? - params[:save_checkout_history] = row['save_checkout_history'] if row['save_checkout_history'].present? + params[:checkout_icalendar_token] = row["checkout_icalendar_token"] if row["checkout_icalendar_token"].present? + params[:save_checkout_history] = row["save_checkout_history"] if row["save_checkout_history"].present? end if defined?(EnjuSearchLog) - params[:save_search_history] = row['save_search_history'] if row['save_search_history'].present? + params[:save_search_history] = row["save_search_history"] if row["save_search_history"].present? end if defined?(EnjuBookmark) - params[:share_bookmarks] = row['share_bookmarks'] if row['share_bookmarks'].present? + params[:share_bookmarks] = row["share_bookmarks"] if row["share_bookmarks"].present? end params end diff --git a/app/models/user_import_file_state_machine.rb b/app/models/user_import_file_state_machine.rb index 0aeb670672..045d8ab8b4 100644 --- a/app/models/user_import_file_state_machine.rb +++ b/app/models/user_import_file_state_machine.rb @@ -6,8 +6,8 @@ class UserImportFileStateMachine state :completed state :failed - transition from: :pending, to: [:started, :failed] - transition from: :started, to: [:completed, :failed] + transition from: :pending, to: [ :started, :failed ] + transition from: :started, to: [ :completed, :failed ] after_transition(from: :pending, to: :started) do |user_import_file| user_import_file.update_column(:executed_at, Time.zone.now) diff --git a/app/models/user_import_file_transition.rb b/app/models/user_import_file_transition.rb index 8feaddc1e7..f64c32495f 100644 --- a/app/models/user_import_file_transition.rb +++ b/app/models/user_import_file_transition.rb @@ -1,7 +1,4 @@ class UserImportFileTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :user_import_file, inverse_of: :user_import_file_transitions end @@ -11,7 +8,7 @@ class UserImportFileTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # user_import_file_id :bigint # created_at :datetime not null diff --git a/app/models/user_import_result.rb b/app/models/user_import_result.rb index 0a32363e87..fa54318f3a 100644 --- a/app/models/user_import_result.rb +++ b/app/models/user_import_result.rb @@ -1,5 +1,5 @@ class UserImportResult < ApplicationRecord - scope :file_id, proc{ |file_id| where(user_import_file_id: file_id) } + scope :file_id, proc { |file_id| where(user_import_file_id: file_id) } scope :failed, -> { where(user_id: nil) } belongs_to :user_import_file diff --git a/app/models/user_reserve_stat.rb b/app/models/user_reserve_stat.rb index a74b28accb..0c21b337bd 100644 --- a/app/models/user_reserve_stat.rb +++ b/app/models/user_reserve_stat.rb @@ -4,8 +4,8 @@ class UserReserveStat < ApplicationRecord initial_state: UserReserveStatStateMachine.initial_state ] include CalculateStat - default_scope {order('user_reserve_stats.id DESC')} - scope :not_calculated, -> {in_state(:pending)} + default_scope { order("user_reserve_stats.id DESC") } + scope :not_calculated, -> { in_state(:pending) } has_many :reserve_stat_has_users, dependent: :destroy has_many :users, through: :reserve_stat_has_users belongs_to :user @@ -28,7 +28,7 @@ def calculate_count! daily_count = user.reserves.created(start_date.beginning_of_day, end_date.tomorrow.beginning_of_day).size if daily_count.positive? users << user - sql = ['UPDATE reserve_stat_has_users SET reserves_count = ? WHERE user_reserve_stat_id = ? AND user_id = ?', daily_count, id, user.id] + sql = [ "UPDATE reserve_stat_has_users SET reserves_count = ? WHERE user_reserve_stat_id = ? AND user_id = ?", daily_count, id, user.id ] UserReserveStat.connection.execute( self.class.send(:sanitize_sql_array, sql) ) diff --git a/app/models/user_reserve_stat_transition.rb b/app/models/user_reserve_stat_transition.rb index b90d0672d6..08a2b0264c 100644 --- a/app/models/user_reserve_stat_transition.rb +++ b/app/models/user_reserve_stat_transition.rb @@ -1,7 +1,4 @@ class UserReserveStatTransition < ApplicationRecord - include Statesman::Adapters::ActiveRecordTransition - - belongs_to :user_reserve_stat, inverse_of: :user_reserve_stat_transitions end @@ -11,7 +8,7 @@ class UserReserveStatTransition < ApplicationRecord # # id :bigint not null, primary key # to_state :string -# metadata :text default({}) +# metadata :jsonb not null # sort_key :integer # user_reserve_stat_id :bigint # created_at :datetime not null diff --git a/app/models/withdraw.rb b/app/models/withdraw.rb index 40d9478545..86df17219a 100644 --- a/app/models/withdraw.rb +++ b/app/models/withdraw.rb @@ -2,10 +2,10 @@ class Withdraw < ApplicationRecord include EnjuCirculation::EnjuWithdraw belongs_to :basket belongs_to :item, touch: true - belongs_to :librarian, class_name: 'User' + belongs_to :librarian, class_name: "User" validates :item_id, - uniqueness: true #{ message: I18n.t('withdraw.already_withdrawn', locale: I18n.default_locale) } + uniqueness: true # { message: I18n.t('withdraw.already_withdrawn', locale: I18n.default_locale) } attr_accessor :item_identifier diff --git a/app/policies/picture_file_policy.rb b/app/policies/picture_file_policy.rb index ab98d0b0d0..5669523234 100644 --- a/app/policies/picture_file_policy.rb +++ b/app/policies/picture_file_policy.rb @@ -29,4 +29,8 @@ def update? def destroy? true if user.try(:has_role?, 'Librarian') end + + def download? + show? + end end diff --git a/app/views/accepts/index.html.erb b/app/views/accepts/index.html.erb index a00b4cf572..b2d37e6bd0 100644 --- a/app/views/accepts/index.html.erb +++ b/app/views/accepts/index.html.erb @@ -1,45 +1,44 @@
-

<%= t('page.listing', model: t('activerecord.models.accept')) -%>

-
+

<%= t('page.listing', model: t('activerecord.models.accept')) -%>

+
+
+ <%= form_for(:accept, html: {method: :get}) do |f| %> +

+ <%= label_tag :item_identifier, t('activerecord.attributes.item.item_identifier') -%>: + <%= f.search_field :item_identifier, value: @query, class: 'resource_item_identifier' -%> + <%= f.submit t('page.search') -%> +

+ <%- end -%> +
-
- <%= form_for(:accept, html: {method: :get}) do |f| %> -

- <%= label_tag :item_identifier, t('activerecord.attributes.item.item_identifier') -%>: - <%= f.search_field :item_identifier, value: @query, class: 'resource_item_identifier' -%> - <%= f.submit t('page.search') -%> -

- <%- end -%> -
- - - - - - - <%- @accepts.each_with_index do |accept, i| -%> - "> - - - - <%- end -%> -
<%= t('activerecord.models.item') -%>
- <% if accept.item %> - <%= render 'manifestations/show_index', manifestation: accept.item.manifestation %> - <%= link_to accept.item.item_identifier, accept.item -%> / <%= accept.item.call_number %> - (<%= link_to accept.item.shelf.library.display_name.localize, accept.item.shelf.library %> / - <%= link_to accept.item.shelf.display_name.localize, accept.item.shelf %>)
- <%=l accept.created_at %> - <% end %> -
- <%- if policy(accept).destroy? -%> - <%= link_to t('page.destroy'), accept, data: {confirm: t('page.are_you_sure')}, method: :delete -%> - <%- end -%> -
- <%= javascript_tag("$(function(){$('#accept_item_identifier').focus()})") %> + + + + + + <%- @accepts.each_with_index do |accept, i| -%> + "> + + + + <%- end -%> +
<%= t('activerecord.models.item') -%>
+ <% if accept.item %> + <%= render 'manifestations/show_index', manifestation: accept.item.manifestation %> + <%= link_to accept.item.item_identifier, accept.item -%> / <%= accept.item.call_number %> + (<%= link_to accept.item.shelf.library.display_name.localize, accept.item.shelf.library %> / + <%= link_to accept.item.shelf.display_name.localize, accept.item.shelf %>)
+ <%=l accept.created_at %> + <% end %> +
+ <%- if policy(accept).destroy? -%> + <%= link_to t('page.destroy'), accept, data: {confirm: t('page.are_you_sure')}, method: :delete -%> + <%- end -%> +
+ <%= javascript_tag("$(function(){$('#accept_item_identifier').focus()})") %> - <%= paginate(@accepts) %> -
+ <%= paginate(@accepts) %> +
diff --git a/app/views/carrier_types/index.html.erb b/app/views/carrier_types/index.html.erb index e68de7c6c1..ab5ed9c593 100644 --- a/app/views/carrier_types/index.html.erb +++ b/app/views/carrier_types/index.html.erb @@ -1,49 +1,49 @@
-

<%= t('page.listing', model: t('activerecord.models.carrier_type')) -%>

-
-

<%= notice %>

+

<%= t('page.listing', model: t('activerecord.models.carrier_type')) -%>

+
+

<%= notice %>

- - - - - - - +
<%= t('activerecord.attributes.carrier_type.name') -%> - <%= t('activerecord.attributes.carrier_type.display_name') -%> - / - <%= t('activerecord.attributes.carrier_type.note') -%> -
+ + + + + + -<%- @carrier_types.each do |carrier_type| -%> - "> - - - - - -<%- end -%> -
<%= t('activerecord.attributes.carrier_type.name') -%> + <%= t('activerecord.attributes.carrier_type.display_name') -%> + / + <%= t('activerecord.attributes.carrier_type.note') -%> +
- <%- if policy(carrier_type).update? -%> - <%= move_position(carrier_type) -%> - <%- end -%> - - <%= image_tag(carrier_type.attachment.representation(resize_to_limit: [16, 16]), size: '16x16', class: 'enju_icon', alt: carrier_type.display_name.localize) %> - <%= carrier_type.name -%> - - <%= link_to carrier_type.display_name.localize, carrier_type -%> -
- <%= carrier_type.note %> -
- <%- if policy(carrier_type).update? -%> - <%= link_to t('page.edit'), edit_carrier_type_path(carrier_type) -%> - <% end %> - <%- if policy(carrier_type).destroy? -%> - <%= link_to t('page.destroy'), carrier_type_path(carrier_type), data: {confirm: t('page.are_you_sure')}, method: :delete -%> - <%- end -%> -
+ <%- @carrier_types.each do |carrier_type| -%> + "> + + <%- if policy(carrier_type).update? -%> + <%= move_position(carrier_type) -%> + <%- end -%> + + + <%= image_tag(carrier_type.attachment.representation(resize_to_limit: [16, 16]), size: '16x16', class: 'enju_icon', alt: carrier_type.display_name.localize) %> + <%= carrier_type.name -%> + + + <%= link_to carrier_type.display_name.localize, carrier_type -%> +
+ <%= carrier_type.note %> + + + <%- if policy(carrier_type).update? -%> + <%= link_to t('page.edit'), edit_carrier_type_path(carrier_type) -%> + <% end %> + <%- if policy(carrier_type).destroy? -%> + <%= link_to t('page.destroy'), carrier_type_path(carrier_type), data: {confirm: t('page.are_you_sure')}, method: :delete -%> + <%- end -%> + + + <%- end -%> + -
+
diff --git a/app/views/event_import_files/show.html.erb b/app/views/event_import_files/show.html.erb index 25e8629b0c..90a01bde42 100644 --- a/app/views/event_import_files/show.html.erb +++ b/app/views/event_import_files/show.html.erb @@ -78,7 +78,7 @@ <% end %> diff --git a/app/views/events/index.html.erb b/app/views/events/index.html.erb index c2caf52128..1d397c8b58 100644 --- a/app/views/events/index.html.erb +++ b/app/views/events/index.html.erb @@ -22,17 +22,17 @@

<%- case params[:mode] when 'upcoming' -%> - <%= link_to t('event.all'), url_for(filtered_params.merge(mode: nil, only_path: true)) -%> + <%= link_to t('event.all'), url_for(filtered_params.merge(only_path: true, mode: nil, only_path: true)) -%> <%= t('event.upcoming') -%> - <%= link_to t('event.past'), url_for(filtered_params.merge(mode: 'past', only_path: true)) -%> + <%= link_to t('event.past'), url_for(filtered_params.merge(only_path: true, mode: 'past', only_path: true)) -%> <%- when 'past' -%> - <%= link_to t('event.all'), url_for(filtered_params.merge(mode: nil, only_path: true)) -%> - <%= link_to t('event.upcoming'), url_for(filtered_params.merge(mode: 'upcoming', only_path: true)) -%> + <%= link_to t('event.all'), url_for(filtered_params.merge(only_path: true, mode: nil, only_path: true)) -%> + <%= link_to t('event.upcoming'), url_for(filtered_params.merge(only_path: true, mode: 'upcoming', only_path: true)) -%> <%= t('event.past') -%> <%- else -%> <%= t('event.all') -%> - <%= link_to t('event.upcoming'), url_for(filtered_params.merge(mode: 'upcoming', only_path: true)) -%> - <%= link_to t('event.past'), url_for(filtered_params.merge(mode: 'past', only_path: true)) -%> + <%= link_to t('event.upcoming'), url_for(filtered_params.merge(only_path: true, mode: 'upcoming', only_path: true)) -%> + <%= link_to t('event.past'), url_for(filtered_params.merge(only_path: true, mode: 'past', only_path: true)) -%> <%- end -%>

@@ -77,9 +77,9 @@ diff --git a/app/views/iiif_presentations/show.json.jbuilder b/app/views/iiif_presentations/show.json.jbuilder index 6a967aa09f..5070595d1c 100644 --- a/app/views/iiif_presentations/show.json.jbuilder +++ b/app/views/iiif_presentations/show.json.jbuilder @@ -1,36 +1,33 @@ -json.set!('@context', 'http://iiif.io/api/presentation/2/context.json') -json.set!('@type', 'sc:Manifest') -json.set!('@id', iiif_presentation_url(@manifestation, format: :json)) +json.set!('@context', 'http://iiif.io/api/presentation/3/context.json') +json.set!('type', 'Manifest') +json.set!('id', iiif_presentation_url(@manifestation)) json.label @manifestation.original_title -json.description @manifestation.description -json.sequences do - json.array! [0] do |a| - json.set!('@type', 'sc:Sequence') - json.viewingHint 'individuals' - json.canvases do - json.array! @manifestation.picture_files do |picture_file| - json.set!('@id', picture_file_url(picture_file)) - json.set!('@type', 'sc:Canvas') - json.label picture_file.attachment.filename - json.width picture_file.attachment.metadata['width'] - json.height picture_file.attachment.metadata['height'] - json.images do - json.array! [0] do |c| - json.set!('@type', 'oa:Annotation') - json.on picture_file_url(picture_file) - json.motivation 'sc:painting' - json.resource do - json.set!('@id', "#{ENV['CANTALOUPE_BASE_URI']}/iiif/3/#{picture_file.id}/full/max/0/default.jpg") - json.set!('@type', 'dctypes:Image') +json.summary @manifestation.description + +json.items do + json.array! @manifestation.picture_files.each_with_index do |picture_file| + json.id picture_file_url(picture_file) + json.type 'Canvas' + json.label picture_file.attachment.filename + json.width picture_file.attachment.metadata['width'] + json.height picture_file.attachment.metadata['height'] + json.format picture_file.attachment.content_type + json.items do + json.array! [0] do + json.id picture_file_url(picture_file) + json.type 'AnnotationPage' + json.items do + json.array! [0] do + json.id picture_file_url(picture_file) + json.type 'Annotation' + json.body do + json.set!('id', "#{ENV['CANTALOUPE_BASE_URL']}/iiif/3/#{picture_file.id}/full/max/0/default.jpg") + json.type 'Image' json.width picture_file.attachment.metadata['width'] json.height picture_file.attachment.metadata['height'] - json.height picture_file.attachment.content_type - json.service do - json.set!('@context', 'http://iiif.io/api/image/3/context.json') - json.set!('@id', "#{ENV['CANTALOUPE_BASE_URI']}/iiif/3/#{picture_file.id}") - json.profile 'http://iiif.io/api/image/3/level1.json' - end + json.format picture_file.attachment.content_type end + json.target picture_file_url(picture_file) end end end diff --git a/app/views/manifestations/_identifier.html.erb b/app/views/manifestations/_identifier.html.erb new file mode 100644 index 0000000000..9bc0dc1eb8 --- /dev/null +++ b/app/views/manifestations/_identifier.html.erb @@ -0,0 +1,21 @@ +<% if manifestation.isbn_records.exists? %> + ISBN: <%= manifestation.isbn_records.pluck(:body).join(' ') %> +<% end %> +<% if manifestation.issn_records.exists? %> + ISSN: <%= manifestation.issn_records.pluck(:body).join(' ') %> +<% end %> +<% if manifestation.ndl_bib_id_record %> +
NDL Search: <%= ndl_bib_id_record_link(manifestation.ndl_bib_id_record) %>
+<% end %> +<% if manifestation.jpno_record %> +
JPNO: <%= manifestation.jpno_record.body %>
+<% end %> +<% if manifestation.ncid_record %> +
NCID: <%= link_to manifestation.ncid_record.body, "https://ci.nii.ac.jp/ncid/#{manifestation.ncid_record.body}" %>
+<% end %> +<% if manifestation.lccn_record %> +
LCCN: <%= manifestation.lccn_record.body %>
+<% end %> +<% if manifestation.doi_record %> +
DOI: <%= link_to manifestation.doi_record.display_body, "https://doi.org/#{manifestation.doi_record.display_body}" %>
+<% end %> diff --git a/app/views/manifestations/_show_detail_librarian.html.erb b/app/views/manifestations/_show_detail_librarian.html.erb index ca490e7e59..0191a72e0c 100644 --- a/app/views/manifestations/_show_detail_librarian.html.erb +++ b/app/views/manifestations/_show_detail_librarian.html.erb @@ -72,6 +72,7 @@ <%= t('page.identifier') -%>: + <%= render 'identifier', manifestation: manifestation %>