diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.dockerignore b/serverside_challenge_1/challenges/ryuichi_ueda/.dockerignore new file mode 100644 index 000000000..bb56dafc1 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.dockerignore @@ -0,0 +1,31 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ + +# Ignore bundler config. +/.bundle + +# Ignore all environment files (except templates). +/.env* +!/.env*.erb + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.gitattributes b/serverside_challenge_1/challenges/ryuichi_ueda/.gitattributes new file mode 100644 index 000000000..8dc432343 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.gitignore b/serverside_challenge_1/challenges/ryuichi_ueda/.gitignore new file mode 100644 index 000000000..7e6b54f49 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.gitignore @@ -0,0 +1,33 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore all environment files (except templates). +/.env* +!/.env*.erb + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.rspec b/serverside_challenge_1/challenges/ryuichi_ueda/.rspec new file mode 100644 index 000000000..c99d2e739 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.rubocop.yml b/serverside_challenge_1/challenges/ryuichi_ueda/.rubocop.yml new file mode 100644 index 000000000..e76114c3b --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.rubocop.yml @@ -0,0 +1,23 @@ +require: rubocop-rails + +AllCops: + TargetRubyVersion: 3.2 + NewCops: enable + Exclude: + - 'db/schema.rb' + - 'bin/*' + - 'node_modules/**/*' +Metrics/MethodLength: + Max: 15 + +Metrics/BlockLength: + Max: 50 + +Style/Documentation: + Enabled: false + +Naming/VariableNumber: + Enabled: false + +Lint/IneffectiveAccessModifier: + Enabled: false \ No newline at end of file diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/.ruby-version b/serverside_challenge_1/challenges/ryuichi_ueda/.ruby-version new file mode 100644 index 000000000..e4604e3af --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/.ruby-version @@ -0,0 +1 @@ +3.2.1 diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/Dockerfile b/serverside_challenge_1/challenges/ryuichi_ueda/Dockerfile new file mode 100644 index 000000000..d147703af --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/Dockerfile @@ -0,0 +1,59 @@ +# syntax = docker/dockerfile:1 + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile +ARG RUBY_VERSION=3.2.1 +FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base + +# Rails app lives here +WORKDIR /rails + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + + +# Throw-away build stage to reduce size of final image +FROM base as build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libvips pkg-config + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + + +# Final stage for app image +FROM base + +# Install packages needed for deployment +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libsqlite3-0 libvips && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Copy built artifacts: gems, application +COPY --from=build /usr/local/bundle /usr/local/bundle +COPY --from=build /rails /rails + +# Run and own only the runtime files as a non-root user for security +RUN useradd rails --create-home --shell /bin/bash && \ + chown -R rails:rails db log storage tmp +USER rails:rails + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start the server by default, this can be overwritten at runtime +EXPOSE 3000 +CMD ["./bin/rails", "server"] diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile b/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile new file mode 100644 index 000000000..879c04796 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +source 'https://rubygems.org' + +ruby '3.2.1' + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem 'rails', '~> 7.1.2' + +# Use sqlite3 as the database for Active Record +gem 'sqlite3', '~> 1.4' + +# Use the Puma web server [https://github.com/puma/puma] +gem 'puma', '>= 5.0' + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +# gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", ">= 4.0.1" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem 'tzinfo-data', platforms: %i[windows jruby] + +# Reduces boot times through caching; required in config/boot.rb +gem 'bootsnap', require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin Ajax possible +# gem "rack-cors" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem 'debug', platforms: %i[mri windows] + gem 'rspec-rails' + gem 'rubocop', require: false + gem 'rubocop-rails' +end + +group :development do + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile.lock b/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile.lock new file mode 100644 index 000000000..e5117548b --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/Gemfile.lock @@ -0,0 +1,260 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.1.2) + actionpack (= 7.1.2) + activesupport (= 7.1.2) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (7.1.2) + actionpack (= 7.1.2) + activejob (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.1.2) + actionpack (= 7.1.2) + actionview (= 7.1.2) + activejob (= 7.1.2) + activesupport (= 7.1.2) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.2) + actionpack (7.1.2) + actionview (= 7.1.2) + activesupport (= 7.1.2) + nokogiri (>= 1.8.5) + racc + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + actiontext (7.1.2) + actionpack (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.1.2) + activesupport (= 7.1.2) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (7.1.2) + activesupport (= 7.1.2) + globalid (>= 0.3.6) + activemodel (7.1.2) + activesupport (= 7.1.2) + activerecord (7.1.2) + activemodel (= 7.1.2) + activesupport (= 7.1.2) + timeout (>= 0.4.0) + activestorage (7.1.2) + actionpack (= 7.1.2) + activejob (= 7.1.2) + activerecord (= 7.1.2) + activesupport (= 7.1.2) + marcel (~> 1.0) + activesupport (7.1.2) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + minitest (>= 5.1) + mutex_m + tzinfo (~> 2.0) + ast (2.4.2) + base64 (0.2.0) + bigdecimal (3.1.4) + bootsnap (1.17.0) + msgpack (~> 1.2) + builder (3.2.4) + concurrent-ruby (1.2.2) + connection_pool (2.4.1) + crass (1.0.6) + date (3.3.4) + debug (1.8.0) + irb (>= 1.5.0) + reline (>= 0.3.1) + diff-lcs (1.5.0) + drb (2.2.0) + ruby2_keywords + erubi (1.12.0) + globalid (1.2.1) + activesupport (>= 6.1) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + io-console (0.6.0) + irb (1.10.1) + rdoc + reline (>= 0.3.8) + json (2.7.1) + language_server-protocol (3.17.0.3) + loofah (2.22.0) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.8.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + mini_mime (1.1.5) + minitest (5.20.0) + msgpack (1.7.2) + mutex_m (0.2.0) + net-imap (0.4.7) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.4.0) + net-protocol + nio4r (2.7.0) + nokogiri (1.15.5-aarch64-linux) + racc (~> 1.4) + nokogiri (1.15.5-arm64-darwin) + racc (~> 1.4) + nokogiri (1.15.5-x86_64-linux) + racc (~> 1.4) + parallel (1.23.0) + parser (3.2.2.4) + ast (~> 2.4.1) + racc + psych (5.1.1.1) + stringio + puma (6.4.0) + nio4r (~> 2.0) + racc (1.7.3) + rack (3.0.8) + rack-session (2.0.0) + rack (>= 3.0.0) + rack-test (2.1.0) + rack (>= 1.3) + rackup (2.1.0) + rack (>= 3) + webrick (~> 1.8) + rails (7.1.2) + actioncable (= 7.1.2) + actionmailbox (= 7.1.2) + actionmailer (= 7.1.2) + actionpack (= 7.1.2) + actiontext (= 7.1.2) + actionview (= 7.1.2) + activejob (= 7.1.2) + activemodel (= 7.1.2) + activerecord (= 7.1.2) + activestorage (= 7.1.2) + activesupport (= 7.1.2) + bundler (>= 1.15.0) + railties (= 7.1.2) + rails-dom-testing (2.2.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.0) + loofah (~> 2.21) + nokogiri (~> 1.14) + railties (7.1.2) + actionpack (= 7.1.2) + activesupport (= 7.1.2) + irb + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.1.0) + rdoc (6.6.1) + psych (>= 4.0.0) + regexp_parser (2.8.3) + reline (0.4.1) + io-console (~> 0.5) + rexml (3.2.6) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-rails (6.1.0) + actionpack (>= 6.1) + activesupport (>= 6.1) + railties (>= 6.1) + rspec-core (~> 3.12) + rspec-expectations (~> 3.12) + rspec-mocks (~> 3.12) + rspec-support (~> 3.12) + rspec-support (3.12.1) + rubocop (1.58.0) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.2.2.4) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.30.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.30.0) + parser (>= 3.2.1.0) + rubocop-rails (2.22.2) + activesupport (>= 4.2.0) + rack (>= 1.1) + rubocop (>= 1.33.0, < 2.0) + rubocop-ast (>= 1.30.0, < 2.0) + ruby-progressbar (1.13.0) + ruby2_keywords (0.0.5) + sqlite3 (1.6.9-aarch64-linux) + sqlite3 (1.6.9-arm64-darwin) + sqlite3 (1.6.9-x86_64-linux) + stringio (3.1.0) + thor (1.3.0) + timeout (0.4.1) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.5.0) + webrick (1.8.1) + websocket-driver (0.7.6) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + zeitwerk (2.6.12) + +PLATFORMS + aarch64-linux + arm64-darwin-21 + x86_64-linux + +DEPENDENCIES + bootsnap + debug + puma (>= 5.0) + rails (~> 7.1.2) + rspec-rails + rubocop + rubocop-rails + sqlite3 (~> 1.4) + tzinfo-data + +RUBY VERSION + ruby 3.2.1p31 + +BUNDLED WITH + 2.4.6 diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/README.md b/serverside_challenge_1/challenges/ryuichi_ueda/README.md new file mode 100644 index 000000000..7db80e4ca --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/README.md @@ -0,0 +1,24 @@ +# README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/Rakefile b/serverside_challenge_1/challenges/ryuichi_ueda/Rakefile new file mode 100644 index 000000000..488c551fe --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/Rakefile @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/channel.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..9aec23053 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/channel.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/connection.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..8d6c2a1bf --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/channels/application_cable/connection.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/api/v1/plans_controller.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/api/v1/plans_controller.rb new file mode 100644 index 000000000..686d7e6ad --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/api/v1/plans_controller.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true + +module Api + module V1 + class PlansController < ApplicationController + include Constants + + before_action :set_params + before_action :validate_params + + def list + totals = ProviderService.calculate(@ampere, @usage) + providers_info = ProviderService.providers_info(@ampere) + generated_data = generate_data(totals, providers_info) + + render JsonResponse.ok(generated_data) + end + + private + + def set_params + @ampere = params[:ampere] + @usage = params[:usage] + end + + def validate_params + validator = Validator.new(@ampere, @usage) + if validator.valid? + @ampere = validator.ampere.to_i + @usage = validator.usage.to_i + else + error_messages = validator.errors.full_messages.join(', ') + render JsonResponse.unprocessable_entity(error_messages) + end + end + + def generate_data(totals, providers_info) + providers_info.map do |provider, info| + { + provider_name: info.keys.first, + plan_name: info.values.first, + price: totals[provider] + } + end + end + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/application_controller.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/application_controller.rb new file mode 100644 index 000000000..edc1deb7c --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/application_controller.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +class ApplicationController < ActionController::API + def route_not_found + render status: :not_found, json: { + status: 'error', + message: 'リクエストされたエンドポイントが見つかりません。', + data: {} + } + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/concerns/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/jobs/application_job.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/jobs/application_job.rb new file mode 100644 index 000000000..bef395997 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/jobs/application_job.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/mailers/application_mailer.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/mailers/application_mailer.rb new file mode 100644 index 000000000..d84cb6e71 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/mailers/application_mailer.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/models/application_record.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/application_record.rb new file mode 100644 index 000000000..08dc53798 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/application_record.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/models/concerns/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/models/concerns/constants.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/concerns/constants.rb new file mode 100644 index 000000000..73bbc568e --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/concerns/constants.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +module Constants + VALID_AMPERES = [10, 15, 20, 30, 40, 50, 60].freeze + VALID_AMPERES_MORE_THAN_30 = [30, 40, 50, 60].freeze + YAML_PATH = Rails.root.join('lib/data/charge_list.yml') +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/models/electric_plan.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/electric_plan.rb new file mode 100644 index 000000000..98906d5b9 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/models/electric_plan.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +class ElectricPlan + def initialize(provider, plan) + @data = InitializeChargePlan.new(provider, plan) + end + + def total_charge(ampere, usage) + (basic_charge(ampere) + usage_charge(usage)).floor + end + + def provider_info + { @data.provider => @data.plan } + end + + protected + + def basic_charge(ampere) + @data.basic_charges[ampere] + end + + def usage_charge(usage) + charge = 0 + @data.tiers.each do |limit, rate| + if usage > limit + charge += (limit * rate) + usage -= limit + else + charge += (usage * rate) + break + end + end + charge + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/services/electric_plan_factory.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/electric_plan_factory.rb new file mode 100644 index 000000000..02546357c --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/electric_plan_factory.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class ElectricPlanFactory + def self.create(provide, plan) + ElectricPlan.new(provide, plan) + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/services/initialize_charge_plan.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/initialize_charge_plan.rb new file mode 100644 index 000000000..7b181d7df --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/initialize_charge_plan.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +class InitializeChargePlan + include Constants + + attr_reader :basic_charges, :tiers, :provider, :plan + + def initialize(provider, plan) + @provider_data = self.class.load_providers[provider] + @basic_charges = generate_basic_charges + @tiers = generate_tiers + @plan = plan || @provider_data['plan'] + @provider = provider + end + + def self.load_providers + @load_providers ||= YAML.load_file(YAML_PATH)['providers'] + end + + private + + def generate_basic_charges + VALID_AMPERES.index_with do |ampere| + @provider_data['basic_charges'][ampere] + end.freeze + end + + def generate_tiers + @provider_data['tiers'].transform_keys do |key| + key == 'Infinity' ? Float::INFINITY : key + end.freeze + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/services/json_response.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/json_response.rb new file mode 100644 index 000000000..3a93cdceb --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/json_response.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +class JsonResponse + def self.unprocessable_entity(message) + { + status: :unprocessable_entity, + json: { + status: 'error', + message:, + data: {} + } + } + end + + def self.ok(generated_data) + { + status: :ok, + json: { + status: 'success', + message: '料金情報の取得に成功しました。', + data: generated_data + } + } + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/services/provider_service.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/provider_service.rb new file mode 100644 index 000000000..e92d3463d --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/provider_service.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true + +class ProviderService + include Constants + + def self.calculate(ampere, usage) + plan_infos = initialize_plans + plans = select_plans(plan_infos, ampere) + plans.to_h do |provider, plan| + [provider, ElectricPlanFactory.create(provider, plan).total_charge(ampere, usage)] + end + end + + def self.providers_info(ampere) + plan_infos = initialize_plans + plans = select_plans(plan_infos, ampere) + plans.to_h do |provider, plan| + [provider, ElectricPlanFactory.create(provider, plan).provider_info] + end + end + + def self.more_than_30_ampere?(ampere) + VALID_AMPERES_MORE_THAN_30.include?(ampere) + end + + def self.select_plans(plan_infos, ampere) + if more_than_30_ampere?(ampere) + plan_infos + else + plan_infos.slice('東京電力エナジーパートナー', 'Loopでんき') + end + end + + def self.initialize_plans + [ + ElectricPlanFactory.create('東京電力エナジーパートナー', '従量電灯B'), + ElectricPlanFactory.create('Loopでんき', 'おうちプラン'), + ElectricPlanFactory.create('東京ガス株式会社', 'ずっとも電気1'), + ElectricPlanFactory.create('JXTGでんき', '従量電灯Bたっぷりプラン') + ].map(&:provider_info).reduce({}, :merge) + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/services/validator.rb b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/validator.rb new file mode 100644 index 000000000..7bbcdbdb3 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/services/validator.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +class Validator + include ActiveModel::Validations + include Constants + + attr_accessor :ampere, :usage + + validate :validate_ampere + validate :validate_usage + + def initialize(ampere, usage) + @ampere = ampere + @usage = usage + end + + private + + def validate_ampere + return if numeric?(@ampere) && VALID_AMPERES.include?(@ampere.to_i) + + errors.add(:ampere, "は#{VALID_AMPERES.join(',')}のいずれかの整数でなければなりません。") + end + + def validate_usage + return if numeric?(@usage) && @usage.to_i >= 0 + + errors.add(:usage, 'は0以上の整数でなければなりません。') + end + + def numeric?(string) + string.match?(/\A\d+\z/) + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.html.erb b/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..3aac9002e --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + +
+ + + + + + <%= yield %> + + diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.text.erb b/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/bin/bundle b/serverside_challenge_1/challenges/ryuichi_ueda/bin/bundle new file mode 100755 index 000000000..ee73929e5 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/bin/bundle @@ -0,0 +1,109 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/bin/docker-entrypoint b/serverside_challenge_1/challenges/ryuichi_ueda/bin/docker-entrypoint new file mode 100755 index 000000000..67ef49314 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/bin/docker-entrypoint @@ -0,0 +1,8 @@ +#!/bin/bash -e + +# If running the rails server then create or migrate existing database +if [ "${1}" == "./bin/rails" ] && [ "${2}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/bin/rails b/serverside_challenge_1/challenges/ryuichi_ueda/bin/rails new file mode 100755 index 000000000..efc037749 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/bin/rake b/serverside_challenge_1/challenges/ryuichi_ueda/bin/rake new file mode 100755 index 000000000..4fbf10b96 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/bin/setup b/serverside_challenge_1/challenges/ryuichi_ueda/bin/setup new file mode 100755 index 000000000..3cd5a9d78 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config.ru b/serverside_challenge_1/challenges/ryuichi_ueda/config.ru new file mode 100644 index 000000000..6dc832180 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config.ru @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application +Rails.application.load_server diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/application.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/application.rb new file mode 100644 index 000000000..004b38211 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/application.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module RyuichiUeda + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.1 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + config.i18n.default_locale = :ja + # Only loads a smaller set of middleware suitable for API only apps. + # Middleware like session, flash, cookies can be added back manually. + # Skip views, helpers and assets when generating a new resource. + config.api_only = true + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/boot.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/boot.rb new file mode 100644 index 000000000..c04863fa7 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/boot.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/cable.yml b/serverside_challenge_1/challenges/ryuichi_ueda/config/cable.yml new file mode 100644 index 000000000..43f3e8b78 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: ryuichi_ueda_production diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/credentials.yml.enc b/serverside_challenge_1/challenges/ryuichi_ueda/config/credentials.yml.enc new file mode 100644 index 000000000..5f2e4a4a8 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/credentials.yml.enc @@ -0,0 +1 @@ +Rp5kc/4wtA5GWGHy7Xzyc6wWc/A05nfNVcsZ6yxMjH8COjaPcY7RMxzwTm+8Lqy/KJL3vcbJLTiuVBTK2JAKt2Ip0wnsszLieAhp/nC10MzqaSrnRMoEedpSu1IcYslaeAxvwF9eAFXhbRWi8CHLNQdcP3I2hJeag0/CKyxI5AHzsDenJmUWWHbdnkZhfIB/9oiERC197Npx4Wxwann3FE7D6G6qfYbX+qjKDV3p1FSD/DV7HSddPutouYhXwfGNiK3q8hpdlKeDj+wIIXFc/BrYLjW3B4fJW4Y/nxpBmZjoN/JtnZiJSJsoaZOXz68sSPPAD4hTtzGs0M3Iq67qZGTv72XVZDfej54gNmwMQiuYuc4ShqbNDkQIIYWrGKeavasjjgP4bxIlvJ4L5ukzzYv3oB0R--CtyHNP83E1O80JeS--vu72EoF/aTgcq6CwYk6e3g== \ No newline at end of file diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/database.yml b/serverside_challenge_1/challenges/ryuichi_ueda/config/database.yml new file mode 100644 index 000000000..796466ba2 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: storage/test.sqlite3 + +production: + <<: *default + database: storage/production.sqlite3 diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/environment.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/environment.rb new file mode 100644 index 000000000..d5abe5580 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/environment.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/development.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/development.rb new file mode 100644 index 000000000..d55362d43 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/development.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/production.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/production.rb new file mode 100644 index 000000000..56862e9b2 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/production.rb @@ -0,0 +1,92 @@ +# frozen_string_literal: true + +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + + # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment + # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. + # config.public_file_server.enabled = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. + # config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Log to STDOUT by default + config.logger = ActiveSupport::Logger.new($stdout) + .tap { |logger| logger.formatter = Logger::Formatter.new } + .then { |logger| ActiveSupport::TaggedLogging.new(logger) } + + # Prepend all log lines with the following tags. + config.log_tags = [:request_id] + + # Info include generic and useful information about system operation, but avoids logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). If you + # want to log everything, set the level to "debug". + config.log_level = ENV.fetch('RAILS_LOG_LEVEL', 'info') + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "ryuichi_ueda_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/test.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/test.rb new file mode 100644 index 000000000..f1d2fb50c --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/environments/test.rb @@ -0,0 +1,66 @@ +# frozen_string_literal: true + +require 'active_support/core_ext/integer/time' + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV['CI'].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/cors.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/cors.rb new file mode 100644 index 000000000..ce5b71a85 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/cors.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true +# Be sure to restart your server when you modify this file. + +# Avoid CORS issues when API is called from the frontend app. +# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests. + +# Read more: https://github.com/cyu/rack-cors + +# Rails.application.config.middleware.insert_before 0, Rack::Cors do +# allow do +# origins "example.com" +# +# resource "*", +# headers: :any, +# methods: [:get, :post, :put, :patch, :delete, :options, :head] +# end +# end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/filter_parameter_logging.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..c416e6a62 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += %i[ + passw secret token _key crypt salt certificate otp ssn +] diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/inflections.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/inflections.rb new file mode 100644 index 000000000..6c78420e7 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/initializers/inflections.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/en.yml b/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/en.yml new file mode 100644 index 000000000..6c349ae5e --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/ja.yml b/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/ja.yml new file mode 100644 index 000000000..2d4215b3b --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/locales/ja.yml @@ -0,0 +1,6 @@ +ja: + activemodel: + attributes: + validator: + ampere: "アンペア" + usage: "使用量" diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/puma.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/puma.rb new file mode 100644 index 000000000..7ed41574c --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/puma.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. + +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +max_threads_count = ENV.fetch('RAILS_MAX_THREADS', 5) +min_threads_count = ENV.fetch('RAILS_MIN_THREADS') { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies that the worker count should equal the number of processors in production. +if ENV['RAILS_ENV'] == 'production' + require 'concurrent-ruby' + worker_count = Integer(ENV.fetch('WEB_CONCURRENCY') { Concurrent.physical_processor_count }) + workers worker_count if worker_count > 1 +end + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +worker_timeout 3600 if ENV.fetch('RAILS_ENV', 'development') == 'development' + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch('PORT', 3000) + +# Specifies the `environment` that Puma will run in. +environment ENV.fetch('RAILS_ENV', 'development') + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch('PIDFILE', 'tmp/pids/server.pid') + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/routes.rb b/serverside_challenge_1/challenges/ryuichi_ueda/config/routes.rb new file mode 100644 index 000000000..c2c758261 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/routes.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get 'up' => 'rails/health#show', as: :rails_health_check + + # Defines the root path route ("/") + # root "posts#index" + namespace :api do + namespace :v1 do + get 'plans/all/:ampere/:usage', to: 'plans#list' + end + end + match '*path', to: 'application#route_not_found', via: :all +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/config/storage.yml b/serverside_challenge_1/challenges/ryuichi_ueda/config/storage.yml new file mode 100644 index 000000000..4942ab669 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/db/seeds.rb b/serverside_challenge_1/challenges/ryuichi_ueda/db/seeds.rb new file mode 100644 index 000000000..07b11e827 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/db/seeds.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/lib/data/charge_list.yml b/serverside_challenge_1/challenges/ryuichi_ueda/lib/data/charge_list.yml new file mode 100644 index 000000000..2a676fdb8 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/lib/data/charge_list.yml @@ -0,0 +1,56 @@ +providers: + "東京電力エナジーパートナー": + plan: "従量電灯B" + basic_charges: + 10: 286.00 + 15: 429.00 + 20: 572.00 + 30: 858.00 + 40: 1144.00 + 50: 1430.00 + 60: 1716.00 + tiers: + 140: 23.67 + 210: 23.88 + .inf: 26.41 + "Loopでんき": + plan: "おうちプラン" + basic_charges: + 10: 0.00 + 15: 0.00 + 20: 0.00 + 30: 0.00 + 40: 0.00 + 50: 0.00 + 60: 0.00 + tiers: + .inf: 26.40 + "東京ガス株式会社": + plan: "ずっとも電気1" + basic_charges: + 10: null + 15: null + 20: null + 30: 858.00 + 40: 1144.00 + 50: 1430.00 + 60: 1716.00 + tiers: + 140: 23.67 + 210: 23.88 + .inf: 26.41 + "JXTGでんき": + plan: "従量電灯Bたっぷりプラン" + basic_charges: + 10: null + 15: null + 20: null + 30: 858.00 + 40: 1144.00 + 50: 1430.00 + 60: 1716.80 + tiers: + 120: 19.88 + 180: 26.48 + 300: 25.08 + .inf: 26.15 \ No newline at end of file diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/lib/tasks/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/log/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/public/robots.txt b/serverside_challenge_1/challenges/ryuichi_ueda/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/controllers/api/v1/plans_controller_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/controllers/api/v1/plans_controller_spec.rb new file mode 100644 index 000000000..fe615453a --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/controllers/api/v1/plans_controller_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Api::V1::PlansController, type: :controller do + describe 'GET #list' do + let(:ampere) { 30 } + let(:usage) { 300 } + let(:totals) { { tokyo_electric: 7993, loop: 7920 } } + let(:providers_info) { { tokyo_electric: { '東京電力エナジーパートナー' => '従量電灯B' }, loop: { 'Loopでんき' => 'おうちプラン' } } } + + before do + allow(ProviderService).to receive(:calculate).and_return(totals) + allow(ProviderService).to receive(:providers_info).and_return(providers_info) + end + + context '有効なパラメータ' do + before { get :list, params: { ampere:, usage: } } + + it 'ProviderServiceが有効なパラメータで呼び出される' do + expect(ProviderService).to have_received(:calculate).with(ampere, usage) + expect(ProviderService).to have_received(:providers_info).with(ampere) + end + + it 'ステータスsuccessと適切なdataが返される' do + expect(response).to have_http_status(:ok) + expect(response.parsed_body).to eq( + 'status' => 'success', + 'message' => '料金情報の取得に成功しました。', + 'data' => [ + { 'provider_name' => '東京電力エナジーパートナー', 'plan_name' => '従量電灯B', 'price' => 7993 }, + { 'provider_name' => 'Loopでんき', 'plan_name' => 'おうちプラン', 'price' => 7920 } + ] + ) + end + end + + context '無効なパラメータ' do + before { get :list, params: { ampere: -1, usage: -1 } } + + it 'ステータスunprocessable_entityでエラーが返される' do + expect(response).to have_http_status(:unprocessable_entity) + expect(response.parsed_body['status']).to eq('error') + end + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/models/electric_plan_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/models/electric_plan_spec.rb new file mode 100644 index 000000000..00c1f3374 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/models/electric_plan_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ElectricPlan do + let(:provider) { '東京電力エナジーパートナー' } + let(:plan) { '従量電灯B' } + let(:electric_plan) { ElectricPlan.new(provider, plan) } + let(:initialize_data) do + instance_double('InitializeChargePlan', provider:, plan: '従量電灯B', basic_charges: { + 10 => 286.00, + 15 => 429.00, + 20 => 572.00, + 30 => 858.00, + 40 => 1144.00, + 50 => 1430.00, + 60 => 1716.00 + }, + tiers: { + 140 => 23.67, + 210 => 23.88, + Float::INFINITY => 26.41 + }) + end + + before do + allow(InitializeChargePlan).to receive(:new).with(provider, plan).and_return(initialize_data) + end + + describe '#total_charge' do + it '正しい合計料金が計算される' do + expect(electric_plan.total_charge(30, 300)).to eq(7992) + end + end + + describe '#provider_info' do + it 'プロバイダーに紐づくプランが返される' do + expect(electric_plan.provider_info).to eq({ provider => '従量電灯B' }) + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/rails_helper.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/rails_helper.rb new file mode 100644 index 000000000..254658cb2 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/rails_helper.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort('The Rails environment is running in production mode!') if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Rails.root.glob('spec/support/**/*.rb').sort.each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + abort e.to_s.strip +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_paths = [ + Rails.root.join('spec/fixtures') + ] + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://rspec.info/features/6-0/rspec-rails + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/routing/plans_routing_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/routing/plans_routing_spec.rb new file mode 100644 index 000000000..72d51e711 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/routing/plans_routing_spec.rb @@ -0,0 +1,22 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe 'ルーティングテスト', type: :routing do + it 'ルーティング to plans#list' do + expect(get: 'api/v1/plans/all/10/100').to route_to( + controller: 'api/v1/plans', + action: 'list', + ampere: '10', + usage: '100' + ) + end + + it '無効なルーティングは route_not_found にリダイレクトされる' do + expect(get: 'api/v1/plans/undefined/10/100').to route_to( + controller: 'application', + action: 'route_not_found', + path: 'api/v1/plans/undefined/10/100' + ) + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/initialize_charge_plan_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/initialize_charge_plan_spec.rb new file mode 100644 index 000000000..5060013bc --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/initialize_charge_plan_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe InitializeChargePlan do + let(:provider) { '東京ガス株式会社' } + let(:plan) { 'ずっとも電気1' } + + before do + allow(YAML).to receive(:load_file).and_call_original + InitializeChargePlan.instance_variable_set(:@providers_data_cache, nil) + end + + subject(:initialize_data) { described_class.new(provider, plan) } + + describe '#initialize' do + it 'YAML.load_fileが2度目以降はキャッシュを使う' do + InitializeChargePlan.load_providers + InitializeChargePlan.load_providers + expect(YAML).to have_received(:load_file).once + end + + it 'プロバイダー情報が正確にロードされる' do + expect(initialize_data.provider).to eq(provider) + expect(initialize_data.plan).to eq('ずっとも電気1') + expect(initialize_data.basic_charges).to eq({ 10 => nil, 15 => nil, 20 => nil, 30 => 858.00, 40 => 1144.00, + 50 => 1430.00, 60 => 1716.00 }) + expect(initialize_data.tiers).to eq(140 => 23.67, 210 => 23.88, Float::INFINITY => 26.41) + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/json_response_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/json_response_spec.rb new file mode 100644 index 000000000..2bbc9e315 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/json_response_spec.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe JsonResponse do + describe '.unprocessable_entity' do + let(:message) { 'エラーメッセージ' } + + it '処理できないunprocessable_entityレスポンスを返す' do + response = JsonResponse.unprocessable_entity(message) + + expect(response).to eq({ + status: :unprocessable_entity, + json: { + status: 'error', + message:, + data: {} + } + }) + end + end + + describe '.ok' do + let(:generated_data) do + [{ + provider_name: '東京電力エナジーパートナー', + plan_name: '従量電灯B', + price: 53_023 + }] + end + + it '正常なレスポンスを返す' do + response = JsonResponse.ok(generated_data) + + expect(response).to eq({ + status: :ok, + json: { + status: 'success', + message: '料金情報の取得に成功しました。', + data: generated_data + } + }) + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/provider_service_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/provider_service_spec.rb new file mode 100644 index 000000000..89fec0a15 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/provider_service_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ProviderService do + let(:ampere_under_30) { 20 } + let(:ampere_over_30) { 40 } + let(:usage) { 100 } + + describe '.calculate' do + context 'アンペア30未満の場合' do + it 'TokyoElectricとLoopの結果のみを返す' do + expect(ProviderService.calculate(ampere_under_30, usage)).to include('東京電力エナジーパートナー', 'Loopでんき') + expect(ProviderService.calculate(ampere_under_30, usage)).not_to include('東京ガス株式会社', 'JXTGでんき') + end + end + + context 'アンペア30以上の場合' do + it '全プロバイダーの結果を返す' do + expect(ProviderService.calculate(ampere_over_30, + usage)).to include('東京電力エナジーパートナー', 'Loopでんき', '東京ガス株式会社', 'JXTGでんき') + end + end + end + + describe '.providers_info' do + context 'アンペア30未満の場合' do + it 'TokyoElectricとLoopの結果のみを返す' do + expect(ProviderService.providers_info(ampere_under_30)).to include('東京電力エナジーパートナー', 'Loopでんき') + expect(ProviderService.providers_info(ampere_under_30)).not_to include('東京ガス株式会社', 'JXTGでんき') + end + end + + context 'アンペア30以上の場合' do + it '全プロバイダーの結果を返す' do + expect(ProviderService.providers_info(ampere_over_30)).to include('東京電力エナジーパートナー', 'Loopでんき', '東京ガス株式会社', + 'JXTGでんき') + end + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/validator_spec.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/validator_spec.rb new file mode 100644 index 000000000..29a01429b --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/services/validator_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Validator do + let(:valid_ampere) { Validator::VALID_AMPERES.first.to_s } + let(:invalid_ampere) { 'あ' } + let(:valid_usage) { '100' } + let(:invalid_usage) { '-10' } + let(:non_numeric_string) { 'abc' } + + describe '#validate' do + context '有効なアンペアと使用量' do + subject { Validator.new(valid_ampere, valid_usage) } + + it 'trueを返す' do + expect(subject.valid?).to be true + end + end + + context '無効なアンペア(数字外の文字列を含む)' do + subject { Validator.new(non_numeric_string, valid_usage) } + + it 'falseを返す' do + expect(subject.valid?).to be false + end + + it 'エラーメッセージが適切' do + subject.valid? + expect(subject.errors[:ampere]).to include('は10,15,20,30,40,50,60のいずれかの整数でなければなりません。') + end + end + + context '無効な使用量(数字外の文字列を含む)' do + subject { Validator.new(valid_ampere, non_numeric_string) } + + it 'falseを返す' do + expect(subject.valid?).to be false + end + + it 'エラーメッセージが適切' do + subject.valid? + expect(subject.errors[:usage]).to include('は0以上の整数でなければなりません。') + end + end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/spec/spec_helper.rb b/serverside_challenge_1/challenges/ryuichi_ueda/spec/spec_helper.rb new file mode 100644 index 000000000..409c64b6c --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/spec/spec_helper.rb @@ -0,0 +1,94 @@ +# frozen_string_literal: true + +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. + # # This allows you to limit a spec run to individual examples or groups + # # you care about by tagging them with `:focus` metadata. When nothing + # # is tagged with `:focus`, all examples get run. RSpec also provides + # # aliases for `it`, `describe`, and `context` that include `:focus` + # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + # config.filter_run_when_matching :focus + # + # # Allows RSpec to persist some state between runs in order to support + # # the `--only-failures` and `--next-failure` CLI options. We recommend + # # you configure your source control system to ignore this file. + # config.example_status_persistence_file_path = "spec/examples.txt" + # + # # Limits the available syntax to the non-monkey patched syntax that is + # # recommended. For more details, see: + # # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + # config.disable_monkey_patching! + # + # # Many RSpec users commonly either run the entire suite or an individual + # # file, and it's useful to allow more verbose output when running an + # # individual spec file. + # if config.files_to_run.one? + # # Use the documentation formatter for detailed output, + # # unless a formatter has already been configured + # # (e.g. via a command-line flag). + # config.default_formatter = "doc" + # end + # + # # Print the 10 slowest examples and example groups at the + # # end of the spec run, to help surface which specs are running + # # particularly slow. + # config.profile_examples = 10 + # + # # Run specs in random order to surface order dependencies. If you find an + # # order dependency and want to debug it, you can fix the order by providing + # # the seed, which is printed after each run. + # # --seed 1234 + # config.order = :random + # + # # Seed global randomization in this process using the `--seed` CLI option. + # # Setting this allows you to use `--seed` to deterministically reproduce + # # test failures related to randomization by passing the same `--seed` value + # # as the one that triggered the failure. + # Kernel.srand config.seed +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/storage/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/channels/application_cable/connection_test.rb b/serverside_challenge_1/challenges/ryuichi_ueda/test/channels/application_cable/connection_test.rb new file mode 100644 index 000000000..4aee9b335 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/test/channels/application_cable/connection_test.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require 'test_helper' + +module ApplicationCable + class ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/controllers/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/fixtures/files/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/integration/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/mailers/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/models/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/test/test_helper.rb b/serverside_challenge_1/challenges/ryuichi_ueda/test/test_helper.rb new file mode 100644 index 000000000..0c92e8e88 --- /dev/null +++ b/serverside_challenge_1/challenges/ryuichi_ueda/test/test_helper.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +require 'rails/test_help' + +module ActiveSupport + class TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/tmp/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/tmp/pids/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/tmp/storage/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/tmp/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/serverside_challenge_1/challenges/ryuichi_ueda/vendor/.keep b/serverside_challenge_1/challenges/ryuichi_ueda/vendor/.keep new file mode 100644 index 000000000..e69de29bb