github-to-canvas-quiz 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (64) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/.rubocop.yml +48 -0
  4. data/CODE_OF_CONDUCT.md +84 -0
  5. data/Gemfile +5 -0
  6. data/LICENSE.txt +21 -0
  7. data/NOTES.md +53 -0
  8. data/README.md +89 -0
  9. data/Rakefile +8 -0
  10. data/bin/console +29 -0
  11. data/bin/github-to-canvas-quiz +15 -0
  12. data/bin/setup +8 -0
  13. data/github-to-canvas-quiz.gemspec +50 -0
  14. data/lib/github_to_canvas_quiz/builder/quiz.rb +110 -0
  15. data/lib/github_to_canvas_quiz/canvas_api/client.rb +80 -0
  16. data/lib/github_to_canvas_quiz/canvas_api/endpoints/quiz_questions.rb +29 -0
  17. data/lib/github_to_canvas_quiz/canvas_api/endpoints/quizzes.rb +25 -0
  18. data/lib/github_to_canvas_quiz/canvas_api/endpoints.rb +10 -0
  19. data/lib/github_to_canvas_quiz/cli.rb +31 -0
  20. data/lib/github_to_canvas_quiz/markdown_builder.rb +90 -0
  21. data/lib/github_to_canvas_quiz/markdown_converter.rb +44 -0
  22. data/lib/github_to_canvas_quiz/model/answer/fill_in_multiple_blanks.rb +34 -0
  23. data/lib/github_to_canvas_quiz/model/answer/matching.rb +35 -0
  24. data/lib/github_to_canvas_quiz/model/answer/multiple_answers.rb +33 -0
  25. data/lib/github_to_canvas_quiz/model/answer/multiple_choice.rb +33 -0
  26. data/lib/github_to_canvas_quiz/model/answer/multiple_dropdowns.rb +34 -0
  27. data/lib/github_to_canvas_quiz/model/answer/short_answer.rb +33 -0
  28. data/lib/github_to_canvas_quiz/model/answer/true_false.rb +33 -0
  29. data/lib/github_to_canvas_quiz/model/question.rb +61 -0
  30. data/lib/github_to_canvas_quiz/model/quiz.rb +62 -0
  31. data/lib/github_to_canvas_quiz/parser/canvas/answer/base.rb +19 -0
  32. data/lib/github_to_canvas_quiz/parser/canvas/answer/fill_in_multiple_blanks.rb +30 -0
  33. data/lib/github_to_canvas_quiz/parser/canvas/answer/matching.rb +31 -0
  34. data/lib/github_to_canvas_quiz/parser/canvas/answer/multiple_answers.rb +33 -0
  35. data/lib/github_to_canvas_quiz/parser/canvas/answer/multiple_choice.rb +33 -0
  36. data/lib/github_to_canvas_quiz/parser/canvas/answer/multiple_dropdowns.rb +30 -0
  37. data/lib/github_to_canvas_quiz/parser/canvas/answer/short_answer.rb +29 -0
  38. data/lib/github_to_canvas_quiz/parser/canvas/answer/true_false.rb +29 -0
  39. data/lib/github_to_canvas_quiz/parser/canvas/answer.rb +34 -0
  40. data/lib/github_to_canvas_quiz/parser/canvas/helpers.rb +25 -0
  41. data/lib/github_to_canvas_quiz/parser/canvas/question.rb +55 -0
  42. data/lib/github_to_canvas_quiz/parser/canvas/quiz.rb +44 -0
  43. data/lib/github_to_canvas_quiz/parser/markdown/answer/base.rb +22 -0
  44. data/lib/github_to_canvas_quiz/parser/markdown/answer/fill_in_multiple_blanks.rb +21 -0
  45. data/lib/github_to_canvas_quiz/parser/markdown/answer/matching.rb +23 -0
  46. data/lib/github_to_canvas_quiz/parser/markdown/answer/multiple_answers.rb +21 -0
  47. data/lib/github_to_canvas_quiz/parser/markdown/answer/multiple_choice.rb +19 -0
  48. data/lib/github_to_canvas_quiz/parser/markdown/answer/multiple_dropdowns.rb +21 -0
  49. data/lib/github_to_canvas_quiz/parser/markdown/answer/short_answer.rb +21 -0
  50. data/lib/github_to_canvas_quiz/parser/markdown/answer/true_false.rb +21 -0
  51. data/lib/github_to_canvas_quiz/parser/markdown/answer.rb +34 -0
  52. data/lib/github_to_canvas_quiz/parser/markdown/base.rb +22 -0
  53. data/lib/github_to_canvas_quiz/parser/markdown/helpers/node_parser.rb +21 -0
  54. data/lib/github_to_canvas_quiz/parser/markdown/helpers/node_scanner.rb +208 -0
  55. data/lib/github_to_canvas_quiz/parser/markdown/question.rb +76 -0
  56. data/lib/github_to_canvas_quiz/parser/markdown/quiz.rb +42 -0
  57. data/lib/github_to_canvas_quiz/repository_interface.rb +42 -0
  58. data/lib/github_to_canvas_quiz/reverse_markdown/converters/p.rb +20 -0
  59. data/lib/github_to_canvas_quiz/reverse_markdown/converters/pre.rb +51 -0
  60. data/lib/github_to_canvas_quiz/reverse_markdown/register.rb +9 -0
  61. data/lib/github_to_canvas_quiz/synchronizer/quiz.rb +140 -0
  62. data/lib/github_to_canvas_quiz/version.rb +5 -0
  63. data/lib/github_to_canvas_quiz.rb +62 -0
  64. metadata +348 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b9447384b555ce88188b53b1781b61fde9ea90a561ff9aeb43cc4814348c094a
4
+ data.tar.gz: 908ee5738930ccc75f45393974d1153084aae97c25030b53bb1fe8889b0a9289
5
+ SHA512:
6
+ metadata.gz: ff3c1151b55aa5dde13e8ade9e8a9dddefa1401889e01c61a678aa50639c679f99b293b6bfeb07513117a451b52d9863588a1c7a69e4a62e21ef756eb526a114
7
+ data.tar.gz: 80d5f2a76c7674995a39d56639fb1bbeabf2da890a72052ec415a5f36446c6261ebe694dc57e10dffd45225fa6644f1cb8ec20d246162c2288bb0ab61de5bb95
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,48 @@
1
+ require:
2
+ - rubocop-rspec
3
+
4
+ AllCops:
5
+ NewCops: enable
6
+
7
+ Layout/FirstHashElementIndentation:
8
+ EnforcedStyle: consistent
9
+
10
+ Layout/LineLength:
11
+ Exclude:
12
+ - "spec/**/*.rb"
13
+
14
+ Metrics/AbcSize:
15
+ Max: 20
16
+
17
+ Metrics/BlockLength:
18
+ Enabled: false
19
+ # Exclude:
20
+ # - "*.gemspec"
21
+ # - "spec/**/*.rb"
22
+
23
+ Metrics/MethodLength:
24
+ Max: 15
25
+
26
+ RSpec/ExampleLength:
27
+ Enabled: false
28
+
29
+ RSpec/MultipleExpectations:
30
+ Enabled: false
31
+
32
+ RSpec/MultipleMemoizedHelpers:
33
+ Enabled: false
34
+
35
+ Style/Documentation:
36
+ Enabled: false
37
+
38
+ Style/Lambda:
39
+ EnforcedStyle: literal
40
+
41
+ Style/NumericLiterals:
42
+ Enabled: false
43
+
44
+ Style/RegexpLiteral:
45
+ AllowInnerSlashes: true
46
+
47
+ Style/SymbolArray:
48
+ EnforcedStyle: brackets
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at ianholla@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 ihollander
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/NOTES.md ADDED
@@ -0,0 +1,53 @@
1
+ ## Refactor
2
+
3
+ Features:
4
+
5
+ - Add a RepositoryInterface class to allow easier testing of repo commit etc
6
+ functionality and slim down builder/synchronizer classes
7
+ - can read the repo data from the directory (local) or url (GitHub API)
8
+ - rename `build` to `backup` in CLI
9
+ - move a bunch of methods from build/sync to models?? would make more testable.
10
+ questionable if the models should be responsible for saving to file
11
+ system/working with git/interacting with API...
12
+ - issue when syncing: points not updated when questions added/removed?
13
+
14
+ Question:
15
+
16
+ - what is public API for this library, besides the CLI?
17
+ - What class is responsible for loading a quiz from the API?
18
+ - What class is responsible for saving a quiz to the file system?
19
+ - use Capybara/HTML matchers for testing HTML strings?
20
+ - probably not necessary to save repo name to YAML, and may cause more issues
21
+ if repo URL changes...
22
+
23
+ ```rb
24
+ quiz = Quiz.from(:canvas, course_id: 1, quiz_id: 2)
25
+ quiz = Quiz.from(:markdown, path: '')
26
+
27
+ class Quiz
28
+ def self.from(loader, options)
29
+ case loader
30
+ when :api
31
+ # where does the API call happen?
32
+ Parser::Canvas::Quiz.new()
33
+ when :file
34
+ Parser::Markdown::Quiz.new(options[:path])
35
+ end
36
+ end
37
+ end
38
+ ```
39
+
40
+ Syncing notes:
41
+
42
+ - When a question is **removed** and a blueprint is synced:
43
+ - students who have already taken the quiz keep their old score unless the
44
+ quiz is re-graded
45
+ - 11/12 => 11/11
46
+ - Canvas sez: "The quiz has changed significantly since this submission was
47
+ made. This submission may need re-grading."
48
+ - When a question is **added** and a blueprint is synced:
49
+ - students who have already taken the quiz keep their old score unless the
50
+ quiz is re-graded
51
+ - 5/6 => 5/7
52
+ - Canvas sez: "The quiz has changed significantly since this submission was
53
+ made. This submission may need re-grading."
data/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # GithubToCanvasQuiz
2
+
3
+
4
+ A tool for resizing and uploading images to AWS S3.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'github-to-canvas-quiz'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ ```console
17
+ $ bundle install
18
+ ```
19
+
20
+ Or install it yourself as:
21
+
22
+ ```console
23
+ $ gem install github-to-canvas-quiz
24
+ ```
25
+
26
+ ## Configuration
27
+
28
+ Interacting with the Canvas API requires that you have the following environment
29
+ variables set:
30
+
31
+ - `ENV['CANVAS_API_PATH']`
32
+ - The base URL for your institution's Canvas API (`https://flatironlearn.beta.instructure.com/api/v1`)
33
+ - `ENV['CANVAS_API_KEY']`
34
+ - Your [Canvas Access Token](https://canvas.instructure.com/doc/api/file.oauth.html#manual-token-generation)
35
+
36
+ ## Usage
37
+
38
+ This gem provides two key features via the CLI: backing up Canvas quizzes to
39
+ markdown, and updating a Canvas quiz from an existing directory of markdown files.
40
+
41
+ ### Backup
42
+
43
+ To backup a Canvas quiz to the current directory:
44
+
45
+ ```console
46
+ $ github-to-canvas-quiz backup --course $COURSE_ID --quiz $QUIZ_ID
47
+ ```
48
+
49
+ This will create a set of markdown files representing the quiz data (one for the
50
+ quiz itself, and one for each question).
51
+
52
+ ### Align
53
+
54
+ To update a Canvas quiz based on the markdown files in the current directory:
55
+
56
+ ```console
57
+ $ github-to-canvas-quiz align
58
+ ```
59
+
60
+ ## Development
61
+
62
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
63
+ `bundle exec rspec` to run the tests. You can also run `bin/console` for an
64
+ interactive prompt that will allow you to experiment.
65
+
66
+ To install this gem onto your local machine, run `bundle exec rake install`. To
67
+ release a new version, update the version number in `version.rb`, and then run
68
+ `bundle exec rake release`, which will create a git tag for the version, push
69
+ git commits and the created tag, and push the `.gem` file to
70
+ [rubygems.org](https://rubygems.org).
71
+
72
+ ## Contributing
73
+
74
+ Bug reports and pull requests are welcome on GitHub at
75
+ https://github.com/ihollander/flatiron-s3-uploader. This project is intended to
76
+ be a safe, welcoming space for collaboration, and contributors are expected to
77
+ adhere to the
78
+ [code of conduct](https://github.com/ihollander/flatiron-s3-uploader/blob/main/CODE_OF_CONDUCT.md).
79
+
80
+ ## License
81
+
82
+ The gem is available as open source under the terms of the
83
+ [MIT License](https://opensource.org/licenses/MIT).
84
+
85
+ ## Code of Conduct
86
+
87
+ Everyone interacting in the FlatironS3Uploader project's codebases, issue
88
+ trackers, chat rooms and mailing lists is expected to follow the
89
+ [code of conduct](https://github.com/ihollander/flatiron-s3-uploader/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # frozen_string_literal: true
4
+
5
+ lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../lib'))
6
+ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
7
+
8
+ require 'bundler/setup'
9
+ require 'pry'
10
+
11
+ require 'github_to_canvas_quiz'
12
+
13
+ def client
14
+ @client ||= GithubToCanvasQuiz::CanvasAPI::Client.new(api_key: ENV['CANVAS_API_KEY'], host: ENV['CANVAS_API_PATH'])
15
+ end
16
+
17
+ def slugify(string)
18
+ string.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
19
+ end
20
+
21
+ def build_all(course_id, repo_prefix)
22
+ quizzes = client.list_quizzes(course_id)
23
+ quizzes.each do |quiz|
24
+ quiz_path = "./tmp/#{repo_prefix}-quiz-#{slugify(quiz['title'])}"
25
+ GithubToCanvasQuiz::Builder::Quiz.new(client, course_id, quiz['id'], quiz_path).build
26
+ end
27
+ end
28
+
29
+ Pry.start
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ # frozen_string_literal: true
4
+
5
+ lib_dir = File.expand_path(File.join(File.dirname(__FILE__), '../lib'))
6
+ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
7
+
8
+ require 'github_to_canvas_quiz'
9
+
10
+ if ENV['GEM_ENV'] == 'development'
11
+ require 'dotenv'
12
+ Dotenv.overload('.env.development.local')
13
+ end
14
+
15
+ GithubToCanvasQuiz::CLI.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/github_to_canvas_quiz/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'github-to-canvas-quiz'
7
+ spec.version = GithubToCanvasQuiz::VERSION
8
+ spec.authors = ['ihollander']
9
+ spec.email = ['ianholla@gmail.com']
10
+
11
+ spec.summary = 'Synchronize Canvas quiz content with GitHub'
12
+ spec.homepage = 'https://github.com/learn-co-curriculum/github-to-canvas-quiz'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = '>= 2.5.0'
15
+
16
+ spec.metadata['allowed_push_host'] = 'https://rubygems.org'
17
+
18
+ spec.metadata['homepage_uri'] = spec.homepage
19
+ spec.metadata['source_code_uri'] = spec.homepage
20
+ spec.metadata['changelog_uri'] = spec.homepage
21
+
22
+ # Specify which files should be added to the gem when it is released.
23
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject do |f|
26
+ (f == __FILE__) || f.match(/\A(?:(?:test|spec|features)\/|\.(?:git|travis|circleci)|appveyor)/)
27
+ end
28
+ end
29
+ spec.bindir = 'bin'
30
+ spec.executables = 'github-to-canvas-quiz'
31
+ spec.require_paths = ['lib']
32
+
33
+ spec.add_dependency 'front_matter_parser', '~> 1.0'
34
+ spec.add_dependency 'git', '~> 1.9'
35
+ spec.add_dependency 'htmlentities', '~> 4.3'
36
+ spec.add_dependency 'nokogiri', '~> 1.12'
37
+ spec.add_dependency 'redcarpet', '~> 3.5'
38
+ spec.add_dependency 'rest-client', '~> 2.1'
39
+ spec.add_dependency 'reverse_markdown', '~> 2.0'
40
+ spec.add_dependency 'rouge', '~> 3.26'
41
+ spec.add_dependency 'thor', '~> 1.1.0'
42
+ spec.add_development_dependency 'dotenv'
43
+ spec.add_development_dependency 'pry'
44
+ spec.add_development_dependency 'rake'
45
+ spec.add_development_dependency 'rspec', '~> 3.10'
46
+ spec.add_development_dependency 'rubocop'
47
+ spec.add_development_dependency 'rubocop-rspec'
48
+ spec.add_development_dependency 'vcr'
49
+ spec.add_development_dependency 'webmock'
50
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GithubToCanvasQuiz
4
+ # CanvasAPI => Markdown
5
+ module Builder
6
+ # Create markdown files from a Canvas Quiz
7
+ class Quiz
8
+ attr_reader :client, :course_id, :quiz_id, :path
9
+
10
+ def initialize(client, course_id, quiz_id, path = '.')
11
+ @path = path
12
+ @client = client
13
+ @course_id = course_id
14
+ @quiz_id = quiz_id
15
+ end
16
+
17
+ def build
18
+ prepare_directory!
19
+ save_quiz!
20
+ save_questions!
21
+ backup_canvas_to_json!
22
+ commit!
23
+ end
24
+
25
+ private
26
+
27
+ def repo
28
+ @repo ||= RepositoryInterface.new(path)
29
+ end
30
+
31
+ def prepare_directory!
32
+ Dir.mkdir(path) unless Pathname(path).directory?
33
+ end
34
+
35
+ def save_quiz!
36
+ File.write(quiz_readme_path, quiz.to_markdown)
37
+ end
38
+
39
+ def save_questions!
40
+ Dir.mkdir(questions_path) unless Pathname(questions_path).directory?
41
+ questions.each.with_index do |question, index|
42
+ File.write(question_readme_path(index), question.to_markdown)
43
+ end
44
+ end
45
+
46
+ def backup_canvas_to_json!
47
+ quiz = client.get_single_quiz(course_id, quiz_id)
48
+ questions = client.list_questions(course_id, quiz_id)
49
+
50
+ json_data = JSON.pretty_generate({ quiz: quiz, questions: questions })
51
+ File.write(json_path, json_data)
52
+ end
53
+
54
+ def commit!
55
+ repo = RepositoryInterface.new(path)
56
+ repo.commit_files('README.md', 'questions', '.canvas-snapshot.json', 'Created Canvas backup')
57
+ end
58
+
59
+ def json_path
60
+ File.join(path, '.canvas-snapshot.json')
61
+ end
62
+
63
+ def quiz_readme_path
64
+ File.join(path, 'README.md')
65
+ end
66
+
67
+ def questions_path
68
+ File.join(path, 'questions')
69
+ end
70
+
71
+ def question_readme_path(index)
72
+ filename = "#{index.to_s.rjust(2, '0')}.md"
73
+ File.join(questions_path, filename)
74
+ end
75
+
76
+ # Get quiz data from the Canvas API and return a Model::Quiz
77
+ # memoized to prevent unnecessary API calls
78
+ def quiz
79
+ return @quiz if defined? @quiz
80
+
81
+ @quiz = begin
82
+ quiz = Parser::Canvas::Quiz.new(canvas_quiz_data).parse
83
+ # use file path as repo if not present
84
+ quiz.repo = path.split('/').last unless quiz.repo
85
+ quiz
86
+ end
87
+ end
88
+
89
+ def canvas_quiz_data
90
+ quiz_data = client.get_single_quiz(course_id, quiz_id)
91
+ quiz_data.merge({ 'course_id' => course_id })
92
+ end
93
+
94
+ # Get question data from the Canvas API and return an array of Model::Question
95
+ # memoized to prevent unnecessary API calls
96
+ def questions
97
+ @questions ||= canvas_question_data.map do |question_data|
98
+ Parser::Canvas::Question.new(question_data).parse
99
+ end
100
+ end
101
+
102
+ def canvas_question_data
103
+ questions_data = client.list_questions(course_id, quiz_id)
104
+ questions_data.map do |question_data|
105
+ question_data.merge({ 'course_id' => course_id, 'quiz_id' => quiz_id })
106
+ end
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GithubToCanvasQuiz
4
+ module CanvasAPI
5
+ class Client
6
+ include Endpoints
7
+
8
+ attr_reader :host, :api_key
9
+
10
+ def initialize(host:, api_key:)
11
+ @host = host
12
+ @api_key = api_key
13
+ end
14
+
15
+ private
16
+
17
+ def get(endpoint)
18
+ response = RestClient.get(host + endpoint, {
19
+ 'Authorization' => "Bearer #{api_key}"
20
+ })
21
+ JSON.parse(response)
22
+ rescue RestClient::BadRequest => e
23
+ report_error(e)
24
+ end
25
+
26
+ def get_all(endpoint)
27
+ data = []
28
+ url = host + endpoint
29
+ while url
30
+ response = RestClient.get(url, {
31
+ 'Authorization' => "Bearer #{api_key}"
32
+ })
33
+ data += JSON.parse(response)
34
+ url = next_url(response.headers[:link])
35
+ end
36
+ data
37
+ rescue RestClient::BadRequest => e
38
+ report_error(e)
39
+ end
40
+
41
+ def post(endpoint, payload)
42
+ response = RestClient.post(host + endpoint, payload, {
43
+ 'Authorization' => "Bearer #{api_key}"
44
+ })
45
+ JSON.parse(response)
46
+ rescue RestClient::BadRequest => e
47
+ report_error(e)
48
+ end
49
+
50
+ def put(endpoint, payload)
51
+ response = RestClient.put(host + endpoint, payload, {
52
+ 'Authorization' => "Bearer #{api_key}"
53
+ })
54
+ JSON.parse(response)
55
+ rescue RestClient::BadRequest => e
56
+ report_error(e)
57
+ end
58
+
59
+ def delete(endpoint)
60
+ RestClient.delete(host + endpoint, {
61
+ 'Authorization' => "Bearer #{api_key}"
62
+ })
63
+ rescue RestClient::BadRequest => e
64
+ report_error(e)
65
+ end
66
+
67
+ def next_url(link)
68
+ link.split(/,/).detect { |rel| rel.match(/rel="next"/) }.split(/;/).first.strip[1..-2]
69
+ rescue NoMethodError
70
+ nil
71
+ end
72
+
73
+ def report_error(err)
74
+ puts "Request failed. #{err.response.code} status code returned."
75
+ puts JSON.parse(err.response.body)
76
+ abort
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GithubToCanvasQuiz
4
+ module CanvasAPI
5
+ module Endpoints
6
+ module QuizQuestions
7
+ def list_questions(course_id, quiz_id)
8
+ get_all("/courses/#{course_id}/quizzes/#{quiz_id}/questions")
9
+ end
10
+
11
+ def get_single_question(course_id, quiz_id, id)
12
+ get("/courses/#{course_id}/quizzes/#{quiz_id}/questions/#{id}")
13
+ end
14
+
15
+ def create_question(course_id, quiz_id, payload)
16
+ post("/courses/#{course_id}/quizzes/#{quiz_id}/questions", payload)
17
+ end
18
+
19
+ def update_question(course_id, quiz_id, id, payload)
20
+ put("/courses/#{course_id}/quizzes/#{quiz_id}/questions/#{id}", payload)
21
+ end
22
+
23
+ def delete_question(course_id, quiz_id, id)
24
+ delete("/courses/#{course_id}/quizzes/#{quiz_id}/questions/#{id}")
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GithubToCanvasQuiz
4
+ module CanvasAPI
5
+ module Endpoints
6
+ module Quizzes
7
+ def list_quizzes(course_id)
8
+ get_all("/courses/#{course_id}/quizzes")
9
+ end
10
+
11
+ def get_single_quiz(course_id, id)
12
+ get("/courses/#{course_id}/quizzes/#{id}")
13
+ end
14
+
15
+ def create_quiz(course_id, payload)
16
+ post("/courses/#{course_id}/quizzes", payload)
17
+ end
18
+
19
+ def update_quiz(course_id, id, payload)
20
+ put("/courses/#{course_id}/quizzes/#{id}", payload)
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end