├── .gitignore ├── .rspec ├── .rubocop.yml ├── .ruby-version ├── .travis.yml ├── GRAPHQL_API_SPEC.md ├── Gemfile ├── Gemfile.lock ├── Procfile ├── README.md ├── Rakefile ├── app ├── assets │ └── config │ │ └── manifest.js ├── channels │ └── application_cable │ │ ├── channel.rb │ │ └── connection.rb ├── controllers │ ├── application_controller.rb │ ├── concerns │ │ └── .keep │ ├── graphql_controller.rb │ └── user_token_controller.rb ├── graphql │ ├── loaders │ │ ├── favorites_loader.rb │ │ └── record_loader.rb │ ├── mutations │ │ ├── .keep │ │ ├── add_comment.rb │ │ ├── base.rb │ │ ├── create_article.rb │ │ ├── create_user.rb │ │ ├── delete_article.rb │ │ ├── delete_comment.rb │ │ ├── favorite_article.rb │ │ ├── follow_user.rb │ │ ├── sign_in_user.rb │ │ ├── unfavorite_article.rb │ │ ├── unfollow_user.rb │ │ ├── update_article.rb │ │ └── update_user.rb │ ├── realworld_schema.rb │ ├── schema.graphql │ ├── types │ │ ├── .keep │ │ ├── article_type.rb │ │ ├── comment_type.rb │ │ ├── followers_connection_type.rb │ │ ├── mutation_type.rb │ │ ├── query_type.rb │ │ ├── user_edge_type.rb │ │ ├── user_error_type.rb │ │ ├── user_type.rb │ │ └── viewer_type.rb │ └── user_error.rb ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── article.rb │ ├── comment.rb │ ├── concerns │ │ └── .keep │ ├── favorite.rb │ ├── follow.rb │ └── user.rb └── views │ └── layouts │ ├── mailer.html.erb │ └── mailer.text.erb ├── bin ├── bundle ├── rails ├── rake ├── rspec ├── setup └── update ├── config.ru ├── config ├── application.rb ├── boot.rb ├── cable.yml ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── acts_as_taggable_on.rb │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── filter_parameter_logging.rb │ ├── friendly_id.rb │ ├── inflections.rb │ ├── knock.rb │ ├── mime_types.rb │ └── wrap_parameters.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb ├── secrets.yml ├── spring.rb └── storage.yml ├── db ├── migrate │ ├── 20180622093617_create_users.rb │ ├── 20180622112835_create_articles.rb │ ├── 20180622160324_create_friendly_id_slugs.rb │ ├── 20180622173640_create_comments.rb │ ├── 20180622221043_create_favorites.rb │ ├── 20180625175104_create_follows.rb │ ├── 20180625195100_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb │ ├── 20180625195101_add_missing_unique_indices.acts_as_taggable_on_engine.rb │ ├── 20180625195102_add_taggings_counter_cache_to_tags.acts_as_taggable_on_engine.rb │ ├── 20180625195103_add_missing_taggable_index.acts_as_taggable_on_engine.rb │ ├── 20180625195104_change_collation_for_tag_names.acts_as_taggable_on_engine.rb │ └── 20180625195105_add_missing_indexes_on_taggings.acts_as_taggable_on_engine.rb ├── schema.rb └── seeds.rb ├── graphql-schema.png ├── lib └── tasks │ ├── .keep │ └── graphql.rake ├── log └── .keep ├── logo.png ├── public ├── docs │ ├── assets │ │ ├── images │ │ │ ├── graphiql-headers.png │ │ │ ├── graphiql-variables.png │ │ │ ├── graphiql.png │ │ │ ├── menu.png │ │ │ └── navbar.png │ │ ├── style.css │ │ └── webfonts │ │ │ ├── 2C4B9D_B_0.eot │ │ │ ├── 2C4B9D_B_0.ttf │ │ │ ├── 2C4B9D_B_0.woff │ │ │ ├── 2C4B9D_B_0.woff2 │ │ │ ├── 2C4B9D_C_0.eot │ │ │ ├── 2C4B9D_C_0.ttf │ │ │ ├── 2C4B9D_C_0.woff │ │ │ ├── 2C4B9D_C_0.woff2 │ │ │ ├── 2C4B9D_D_0.eot │ │ │ ├── 2C4B9D_D_0.ttf │ │ │ ├── 2C4B9D_D_0.woff │ │ │ ├── 2C4B9D_D_0.woff2 │ │ │ ├── 2C4B9D_E_0.eot │ │ │ ├── 2C4B9D_E_0.ttf │ │ │ ├── 2C4B9D_E_0.woff │ │ │ └── 2C4B9D_E_0.woff2 │ ├── enum │ │ ├── __directivelocation │ │ │ └── index.html │ │ ├── __typekind │ │ │ └── index.html │ │ └── index.html │ ├── index.html │ ├── input_object │ │ ├── addcommentinput │ │ │ └── index.html │ │ ├── createarticleinput │ │ │ └── index.html │ │ ├── createuserinput │ │ │ └── index.html │ │ ├── deletearticleinput │ │ │ └── index.html │ │ ├── deletecommentinput │ │ │ └── index.html │ │ ├── favoritearticleinput │ │ │ └── index.html │ │ ├── followuserinput │ │ │ └── index.html │ │ ├── index.html │ │ ├── signinuserinput │ │ │ └── index.html │ │ ├── unfavoritearticleinput │ │ │ └── index.html │ │ ├── unfollowuserinput │ │ │ └── index.html │ │ ├── updatearticleinput │ │ │ └── index.html │ │ └── updateuserinput │ │ │ └── index.html │ ├── interface │ │ └── index.html │ ├── mutation │ │ ├── addcomment │ │ │ └── index.html │ │ ├── createarticle │ │ │ └── index.html │ │ ├── createuser │ │ │ └── index.html │ │ ├── deletearticle │ │ │ └── index.html │ │ ├── deletecomment │ │ │ └── index.html │ │ ├── favoritearticle │ │ │ └── index.html │ │ ├── followuser │ │ │ └── index.html │ │ ├── signinuser │ │ │ └── index.html │ │ ├── unfavoritearticle │ │ │ └── index.html │ │ ├── unfollowuser │ │ │ └── index.html │ │ ├── updatearticle │ │ │ └── index.html │ │ └── updateuser │ │ │ └── index.html │ ├── object │ │ ├── __directive │ │ │ └── index.html │ │ ├── __enumvalue │ │ │ └── index.html │ │ ├── __field │ │ │ └── index.html │ │ ├── __inputvalue │ │ │ └── index.html │ │ ├── __schema │ │ │ └── index.html │ │ ├── __type │ │ │ └── index.html │ │ ├── addcommentpayload │ │ │ └── index.html │ │ ├── article │ │ │ └── index.html │ │ ├── articleconnection │ │ │ └── index.html │ │ ├── articleedge │ │ │ └── index.html │ │ ├── comment │ │ │ └── index.html │ │ ├── createarticlepayload │ │ │ └── index.html │ │ ├── createuserpayload │ │ │ └── index.html │ │ ├── deletearticlepayload │ │ │ └── index.html │ │ ├── deletecommentpayload │ │ │ └── index.html │ │ ├── favoritearticlepayload │ │ │ └── index.html │ │ ├── followersconnection │ │ │ └── index.html │ │ ├── followuserpayload │ │ │ └── index.html │ │ ├── index.html │ │ ├── pageinfo │ │ │ └── index.html │ │ ├── signinuserpayload │ │ │ └── index.html │ │ ├── unfavoritearticlepayload │ │ │ └── index.html │ │ ├── unfollowuserpayload │ │ │ └── index.html │ │ ├── updatearticlepayload │ │ │ └── index.html │ │ ├── updateuserpayload │ │ │ └── index.html │ │ ├── user │ │ │ └── index.html │ │ ├── useredge │ │ │ └── index.html │ │ ├── usererror │ │ │ └── index.html │ │ └── viewer │ │ │ └── index.html │ ├── operation │ │ ├── mutation │ │ │ └── index.html │ │ └── query │ │ │ └── index.html │ ├── scalar │ │ ├── boolean │ │ │ └── index.html │ │ ├── datetime │ │ │ └── index.html │ │ ├── float │ │ │ └── index.html │ │ ├── id │ │ │ └── index.html │ │ ├── index.html │ │ ├── int │ │ │ └── index.html │ │ ├── iso8601datetime │ │ │ └── index.html │ │ └── string │ │ │ └── index.html │ └── union │ │ └── index.html └── robots.txt ├── spec ├── factories │ ├── articles.rb │ └── users.rb ├── graphql │ ├── mutations │ │ ├── add_comment_spec.rb │ │ ├── create_article_spec.rb │ │ ├── create_user_spec.rb │ │ └── sign_in_user_spec.rb │ └── realword_schema_spec.rb ├── rails_helper.rb ├── spec_helper.rb └── support │ └── factory_bot.rb ├── tmp └── .keep └── vendor └── .keep /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore the default SQLite database. 11 | /db/*.sqlite3 12 | /db/*.sqlite3-journal 13 | 14 | # Ignore all logfiles and tempfiles. 15 | /log/* 16 | /tmp/* 17 | !/log/.keep 18 | !/tmp/.keep 19 | 20 | # Ignore uploaded files in development 21 | /storage/* 22 | 23 | .byebug_history 24 | 25 | # Ignore master key for decrypting credentials and more. 26 | /config/master.key 27 | 28 | /.sass-cache 29 | #/public/docs 30 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --require spec_helper 2 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | Exclude: 3 | - 'bin/**/*' 4 | - 'db/**/*' 5 | - 'config/**/*' 6 | - 'script/**/*' 7 | 8 | Metrics/BlockLength: 9 | Exclude: 10 | - "spec/**/*" 11 | 12 | Metrics/LineLength: 13 | Max: 120 14 | 15 | Metrics/MethodLength: 16 | Max: 20 17 | 18 | Rails: 19 | Enabled: true 20 | 21 | Style/ClassAndModuleChildren: 22 | Enabled: false 23 | 24 | Style/Documentation: 25 | Enabled: false 26 | 27 | Style/FrozenStringLiteralComment: 28 | Enabled: false 29 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | 3.0.2 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 3 | - 2.5.1 4 | script: 5 | - bundle exec rails db:setup 6 | - bundle exec rails spec 7 | cache: bundler 8 | services: 9 | - postgresql 10 | -------------------------------------------------------------------------------- /GRAPHQL_API_SPEC.md: -------------------------------------------------------------------------------- 1 | # RealWorld GraphQL API Spec 2 | 3 | ## Authentication Header: 4 | 5 | `Authorization: Token jwt.token.here` 6 | 7 | ## GraphQL Schema: 8 | 9 | GraphQL Schema graph generated with [GraphQL Voyager](https://github.com/APIs-guru/graphql-voyager): 10 | ![GraphQL Schema graph](graphql-schema.png) 11 | 12 | [GraphiQL Explorer](https://realworld-graphql.herokuapp.com/graphiql) 13 | | 14 | [Documentation](https://realworld-graphql.herokuapp.com/docs) 15 | 16 | This schema can be used with different graphql clients: Relay, Apollo, etc. 17 | 18 | ```GraphQL 19 | # Autogenerated input type of AddComment 20 | input AddCommentInput { 21 | articleId: ID! 22 | body: String! 23 | 24 | # A unique identifier for the client performing the mutation. 25 | clientMutationId: String 26 | } 27 | 28 | # Autogenerated return type of AddComment 29 | type AddCommentPayload { 30 | # A unique identifier for the client performing the mutation. 31 | clientMutationId: String 32 | comment: Comment 33 | errors: [UserError!]! 34 | } 35 | 36 | type Article { 37 | author: User 38 | body: String! 39 | comments: [Comment!]! 40 | createdAt: ISO8601DateTime! 41 | description: String! 42 | favoritesCount: Int! 43 | id: ID! 44 | slug: String! 45 | tagList: [String!]! 46 | title: String! 47 | updatedAt: ISO8601DateTime! 48 | viewerHasFavorited: Boolean! 49 | } 50 | 51 | # The connection type for Article. 52 | type ArticleConnection { 53 | # A list of edges. 54 | edges: [ArticleEdge] 55 | 56 | # Information to aid in pagination. 57 | pageInfo: PageInfo! 58 | } 59 | 60 | # An edge in a connection. 61 | type ArticleEdge { 62 | # A cursor for use in pagination. 63 | cursor: String! 64 | 65 | # The item at the end of the edge. 66 | node: Article 67 | } 68 | 69 | type Comment { 70 | article: Article 71 | author: User 72 | body: String! 73 | createdAt: ISO8601DateTime! 74 | id: ID! 75 | updatedAt: ISO8601DateTime! 76 | } 77 | 78 | # Autogenerated input type of CreateArticle 79 | input CreateArticleInput { 80 | body: String! 81 | 82 | # A unique identifier for the client performing the mutation. 83 | clientMutationId: String 84 | description: String! 85 | tagList: [String!]! 86 | title: String! 87 | } 88 | 89 | # Autogenerated return type of CreateArticle 90 | type CreateArticlePayload { 91 | article: Article 92 | 93 | # A unique identifier for the client performing the mutation. 94 | clientMutationId: String 95 | errors: [UserError!]! 96 | } 97 | 98 | # Autogenerated input type of CreateUser 99 | input CreateUserInput { 100 | # A unique identifier for the client performing the mutation. 101 | clientMutationId: String 102 | email: String! 103 | password: String! 104 | username: String! 105 | } 106 | 107 | # Autogenerated return type of CreateUser 108 | type CreateUserPayload { 109 | # A unique identifier for the client performing the mutation. 110 | clientMutationId: String 111 | errors: [UserError!]! 112 | user: User 113 | } 114 | 115 | # Autogenerated input type of DeleteArticle 116 | input DeleteArticleInput { 117 | # A unique identifier for the client performing the mutation. 118 | clientMutationId: String 119 | id: ID! 120 | } 121 | 122 | # Autogenerated return type of DeleteArticle 123 | type DeleteArticlePayload { 124 | article: Article! 125 | 126 | # A unique identifier for the client performing the mutation. 127 | clientMutationId: String 128 | } 129 | 130 | # Autogenerated input type of DeleteComment 131 | input DeleteCommentInput { 132 | # A unique identifier for the client performing the mutation. 133 | clientMutationId: String 134 | id: ID! 135 | } 136 | 137 | # Autogenerated return type of DeleteComment 138 | type DeleteCommentPayload { 139 | # A unique identifier for the client performing the mutation. 140 | clientMutationId: String 141 | comment: Comment 142 | } 143 | 144 | # Autogenerated input type of FavoriteArticle 145 | input FavoriteArticleInput { 146 | # A unique identifier for the client performing the mutation. 147 | clientMutationId: String 148 | id: ID! 149 | } 150 | 151 | # Autogenerated return type of FavoriteArticle 152 | type FavoriteArticlePayload { 153 | article: Article 154 | 155 | # A unique identifier for the client performing the mutation. 156 | clientMutationId: String 157 | } 158 | 159 | # Autogenerated input type of FollowUser 160 | input FollowUserInput { 161 | # A unique identifier for the client performing the mutation. 162 | clientMutationId: String 163 | id: ID! 164 | } 165 | 166 | # Autogenerated return type of FollowUser 167 | type FollowUserPayload { 168 | # A unique identifier for the client performing the mutation. 169 | clientMutationId: String 170 | user: User 171 | } 172 | 173 | # The connection type for User. 174 | type FollowersConnection { 175 | # A list of edges. 176 | edges: [UserEdge] 177 | 178 | # A list of nodes. 179 | nodes: [User] 180 | 181 | # Information to aid in pagination. 182 | pageInfo: PageInfo! 183 | totalCount: Int! 184 | } 185 | 186 | # An ISO 8601-encoded datetime 187 | scalar ISO8601DateTime 188 | 189 | type Mutation { 190 | addComment(input: AddCommentInput!): AddCommentPayload 191 | createArticle(input: CreateArticleInput!): CreateArticlePayload 192 | createUser(input: CreateUserInput!): CreateUserPayload 193 | deleteArticle(input: DeleteArticleInput!): DeleteArticlePayload 194 | deleteComment(input: DeleteCommentInput!): DeleteCommentPayload 195 | favoriteArticle(input: FavoriteArticleInput!): FavoriteArticlePayload 196 | followUser(input: FollowUserInput!): FollowUserPayload 197 | signInUser(input: SignInUserInput!): SignInUserPayload 198 | unfavoriteArticle(input: UnfavoriteArticleInput!): UnfavoriteArticlePayload 199 | unfollowUser(input: UnfollowUserInput!): UnfollowUserPayload 200 | updateArticle(input: UpdateArticleInput!): UpdateArticlePayload 201 | updateUser(input: UpdateUserInput!): UpdateUserPayload 202 | } 203 | 204 | # Information about pagination in a connection. 205 | type PageInfo { 206 | # When paginating forwards, the cursor to continue. 207 | endCursor: String 208 | 209 | # When paginating forwards, are there more items? 210 | hasNextPage: Boolean! 211 | 212 | # When paginating backwards, are there more items? 213 | hasPreviousPage: Boolean! 214 | 215 | # When paginating backwards, the cursor to continue. 216 | startCursor: String 217 | } 218 | 219 | type Query { 220 | article(slug: String!): Article 221 | articles( 222 | # Returns the elements in the list that come after the specified cursor. 223 | after: String 224 | 225 | # Returns the elements in the list that come before the specified cursor. 226 | before: String 227 | 228 | # Returns the first _n_ elements from the list. 229 | first: Int 230 | 231 | # Returns the last _n_ elements from the list. 232 | last: Int 233 | tag: String 234 | ): ArticleConnection! 235 | tags: [String!]! 236 | user(username: String!): User 237 | viewer: Viewer 238 | } 239 | 240 | # Autogenerated input type of SignInUser 241 | input SignInUserInput { 242 | # A unique identifier for the client performing the mutation. 243 | clientMutationId: String 244 | email: String! 245 | password: String! 246 | } 247 | 248 | # Autogenerated return type of SignInUser 249 | type SignInUserPayload { 250 | # A unique identifier for the client performing the mutation. 251 | clientMutationId: String 252 | errors: [UserError!]! 253 | token: String 254 | viewer: Viewer 255 | } 256 | 257 | # Autogenerated input type of UnfavoriteArticle 258 | input UnfavoriteArticleInput { 259 | # A unique identifier for the client performing the mutation. 260 | clientMutationId: String 261 | id: ID! 262 | } 263 | 264 | # Autogenerated return type of UnfavoriteArticle 265 | type UnfavoriteArticlePayload { 266 | article: Article 267 | 268 | # A unique identifier for the client performing the mutation. 269 | clientMutationId: String 270 | } 271 | 272 | # Autogenerated input type of UnfollowUser 273 | input UnfollowUserInput { 274 | # A unique identifier for the client performing the mutation. 275 | clientMutationId: String 276 | id: ID! 277 | } 278 | 279 | # Autogenerated return type of UnfollowUser 280 | type UnfollowUserPayload { 281 | # A unique identifier for the client performing the mutation. 282 | clientMutationId: String 283 | user: User 284 | } 285 | 286 | # Autogenerated input type of UpdateArticle 287 | input UpdateArticleInput { 288 | body: String! 289 | 290 | # A unique identifier for the client performing the mutation. 291 | clientMutationId: String 292 | description: String! 293 | id: ID! 294 | tagList: [String!]! 295 | title: String! 296 | } 297 | 298 | # Autogenerated return type of UpdateArticle 299 | type UpdateArticlePayload { 300 | article: Article 301 | 302 | # A unique identifier for the client performing the mutation. 303 | clientMutationId: String 304 | errors: [UserError!]! 305 | } 306 | 307 | # Autogenerated input type of UpdateUser 308 | input UpdateUserInput { 309 | bio: String 310 | 311 | # A unique identifier for the client performing the mutation. 312 | clientMutationId: String 313 | email: String! 314 | image: String 315 | password: String 316 | username: String! 317 | } 318 | 319 | # Autogenerated return type of UpdateUser 320 | type UpdateUserPayload { 321 | # A unique identifier for the client performing the mutation. 322 | clientMutationId: String 323 | errors: [UserError!]! 324 | user: User 325 | } 326 | 327 | type User { 328 | articles( 329 | # Returns the elements in the list that come after the specified cursor. 330 | after: String 331 | 332 | # Returns the elements in the list that come before the specified cursor. 333 | before: String 334 | 335 | # Returns the first _n_ elements from the list. 336 | first: Int 337 | 338 | # Returns the last _n_ elements from the list. 339 | last: Int 340 | ): ArticleConnection! 341 | bio: String 342 | email: String! 343 | favoriteArticles( 344 | # Returns the elements in the list that come after the specified cursor. 345 | after: String 346 | 347 | # Returns the elements in the list that come before the specified cursor. 348 | before: String 349 | 350 | # Returns the first _n_ elements from the list. 351 | first: Int 352 | 353 | # Returns the last _n_ elements from the list. 354 | last: Int 355 | ): ArticleConnection! 356 | followedByViewer: Boolean! 357 | followers( 358 | # Returns the elements in the list that come after the specified cursor. 359 | after: String 360 | 361 | # Returns the elements in the list that come before the specified cursor. 362 | before: String 363 | 364 | # Returns the first _n_ elements from the list. 365 | first: Int 366 | 367 | # Returns the last _n_ elements from the list. 368 | last: Int 369 | ): FollowersConnection! 370 | id: ID! 371 | image: String 372 | username: String! 373 | } 374 | 375 | # An edge in a connection. 376 | type UserEdge { 377 | # A cursor for use in pagination. 378 | cursor: String! 379 | 380 | # The item at the end of the edge. 381 | node: User 382 | } 383 | 384 | type UserError { 385 | message: String! 386 | path: String 387 | } 388 | 389 | type Viewer { 390 | feed( 391 | # Returns the elements in the list that come after the specified cursor. 392 | after: String 393 | 394 | # Returns the elements in the list that come before the specified cursor. 395 | before: String 396 | 397 | # Returns the first _n_ elements from the list. 398 | first: Int 399 | 400 | # Returns the last _n_ elements from the list. 401 | last: Int 402 | ): ArticleConnection! 403 | user: User! 404 | } 405 | ``` 406 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '3.0.2' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' 7 | gem 'rails' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg' 10 | # Use Puma as the app server 11 | gem 'puma' 12 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 13 | # gem 'jbuilder', '~> 2.5' 14 | # Use Redis adapter to run Action Cable in production 15 | # gem 'redis', '~> 4.0' 16 | # Use ActiveModel has_secure_password 17 | # gem 'bcrypt', '~> 3.1.7' 18 | 19 | # Use ActiveStorage variant 20 | # gem 'mini_magick', '~> 4.8' 21 | 22 | # Use Capistrano for deployment 23 | # gem 'capistrano-rails', group: :development 24 | 25 | # Reduces boot times through caching; required in config/boot.rb 26 | gem 'bootsnap' 27 | 28 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 29 | gem 'rack-cors' 30 | 31 | gem 'acts-as-taggable-on' 32 | gem 'bcrypt' 33 | gem 'friendly_id' 34 | gem 'knock' 35 | gem 'graphql' 36 | gem 'graphql-batch' 37 | gem 'graphql-docs' 38 | gem 'graphiql-rails' 39 | gem 'graphql-rails_logger' 40 | gem 'newrelic_rpm' 41 | 42 | group :development, :test do 43 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 44 | gem 'byebug', platforms: %i[mri mingw x64_mingw] 45 | end 46 | 47 | group :development do 48 | gem 'listen', '>= 3.0.5', '< 3.2' 49 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 50 | gem 'rubocop', require: false 51 | gem 'spring' 52 | gem 'spring-watcher-listen', '~> 2.0.0' 53 | end 54 | 55 | group :test do 56 | gem 'factory_bot_rails' 57 | gem 'rspec-rails' 58 | end 59 | 60 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 61 | gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] 62 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.1.4.1) 5 | actionpack (= 6.1.4.1) 6 | activesupport (= 6.1.4.1) 7 | nio4r (~> 2.0) 8 | websocket-driver (>= 0.6.1) 9 | actionmailbox (6.1.4.1) 10 | actionpack (= 6.1.4.1) 11 | activejob (= 6.1.4.1) 12 | activerecord (= 6.1.4.1) 13 | activestorage (= 6.1.4.1) 14 | activesupport (= 6.1.4.1) 15 | mail (>= 2.7.1) 16 | actionmailer (6.1.4.1) 17 | actionpack (= 6.1.4.1) 18 | actionview (= 6.1.4.1) 19 | activejob (= 6.1.4.1) 20 | activesupport (= 6.1.4.1) 21 | mail (~> 2.5, >= 2.5.4) 22 | rails-dom-testing (~> 2.0) 23 | actionpack (6.1.4.1) 24 | actionview (= 6.1.4.1) 25 | activesupport (= 6.1.4.1) 26 | rack (~> 2.0, >= 2.0.9) 27 | rack-test (>= 0.6.3) 28 | rails-dom-testing (~> 2.0) 29 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 30 | actiontext (6.1.4.1) 31 | actionpack (= 6.1.4.1) 32 | activerecord (= 6.1.4.1) 33 | activestorage (= 6.1.4.1) 34 | activesupport (= 6.1.4.1) 35 | nokogiri (>= 1.8.5) 36 | actionview (6.1.4.1) 37 | activesupport (= 6.1.4.1) 38 | builder (~> 3.1) 39 | erubi (~> 1.4) 40 | rails-dom-testing (~> 2.0) 41 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 42 | activejob (6.1.4.1) 43 | activesupport (= 6.1.4.1) 44 | globalid (>= 0.3.6) 45 | activemodel (6.1.4.1) 46 | activesupport (= 6.1.4.1) 47 | activerecord (6.1.4.1) 48 | activemodel (= 6.1.4.1) 49 | activesupport (= 6.1.4.1) 50 | activestorage (6.1.4.1) 51 | actionpack (= 6.1.4.1) 52 | activejob (= 6.1.4.1) 53 | activerecord (= 6.1.4.1) 54 | activesupport (= 6.1.4.1) 55 | marcel (~> 1.0.0) 56 | mini_mime (>= 1.1.0) 57 | activesupport (6.1.4.1) 58 | concurrent-ruby (~> 1.0, >= 1.0.2) 59 | i18n (>= 1.6, < 2) 60 | minitest (>= 5.1) 61 | tzinfo (~> 2.0) 62 | zeitwerk (~> 2.3) 63 | acts-as-taggable-on (8.1.0) 64 | activerecord (>= 5.0, < 6.2) 65 | ast (2.4.2) 66 | bcrypt (3.1.16) 67 | bootsnap (1.8.1) 68 | msgpack (~> 1.0) 69 | builder (3.2.4) 70 | byebug (11.1.3) 71 | commonmarker (0.23.0) 72 | concurrent-ruby (1.1.9) 73 | crass (1.0.6) 74 | diff-lcs (1.4.4) 75 | erubi (1.10.0) 76 | escape_utils (1.2.1) 77 | extended-markdown-filter (0.7.0) 78 | html-pipeline (~> 2.9) 79 | factory_bot (6.2.0) 80 | activesupport (>= 5.0.0) 81 | factory_bot_rails (6.2.0) 82 | factory_bot (~> 6.2.0) 83 | railties (>= 5.0.0) 84 | ffi (1.15.4) 85 | friendly_id (5.4.2) 86 | activerecord (>= 4.0.0) 87 | gemoji (3.0.1) 88 | globalid (0.5.2) 89 | activesupport (>= 5.0) 90 | graphiql-rails (1.8.0) 91 | railties 92 | sprockets-rails 93 | graphql (1.12.16) 94 | graphql-batch (0.4.3) 95 | graphql (>= 1.3, < 2) 96 | promise.rb (~> 0.7.2) 97 | graphql-docs (2.0.1) 98 | commonmarker (~> 0.16) 99 | escape_utils (~> 1.2) 100 | extended-markdown-filter (~> 0.4) 101 | gemoji (~> 3.0) 102 | graphql (~> 1.10) 103 | html-pipeline (~> 2.9) 104 | sass (~> 3.4) 105 | graphql-rails_logger (1.2.3) 106 | actionpack (> 5.0) 107 | activesupport (> 5.0) 108 | railties (> 5.0) 109 | rouge (~> 3.0) 110 | html-pipeline (2.14.0) 111 | activesupport (>= 2) 112 | nokogiri (>= 1.4) 113 | i18n (1.8.10) 114 | concurrent-ruby (~> 1.0) 115 | jwt (1.5.6) 116 | knock (2.1.1) 117 | bcrypt (~> 3.1) 118 | jwt (~> 1.5) 119 | rails (>= 4.2) 120 | listen (3.0.8) 121 | rb-fsevent (~> 0.9, >= 0.9.4) 122 | rb-inotify (~> 0.9, >= 0.9.7) 123 | loofah (2.12.0) 124 | crass (~> 1.0.2) 125 | nokogiri (>= 1.5.9) 126 | mail (2.7.1) 127 | mini_mime (>= 0.1.1) 128 | marcel (1.0.1) 129 | method_source (1.0.0) 130 | mini_mime (1.1.1) 131 | minitest (5.14.4) 132 | msgpack (1.4.2) 133 | newrelic_rpm (7.2.0) 134 | nio4r (2.5.8) 135 | nokogiri (1.12.4-x86_64-darwin) 136 | racc (~> 1.4) 137 | parallel (1.20.1) 138 | parser (3.0.2.0) 139 | ast (~> 2.4.1) 140 | pg (1.2.3) 141 | promise.rb (0.7.4) 142 | puma (5.4.0) 143 | nio4r (~> 2.0) 144 | racc (1.5.2) 145 | rack (2.2.3) 146 | rack-cors (1.1.1) 147 | rack (>= 2.0.0) 148 | rack-test (1.1.0) 149 | rack (>= 1.0, < 3) 150 | rails (6.1.4.1) 151 | actioncable (= 6.1.4.1) 152 | actionmailbox (= 6.1.4.1) 153 | actionmailer (= 6.1.4.1) 154 | actionpack (= 6.1.4.1) 155 | actiontext (= 6.1.4.1) 156 | actionview (= 6.1.4.1) 157 | activejob (= 6.1.4.1) 158 | activemodel (= 6.1.4.1) 159 | activerecord (= 6.1.4.1) 160 | activestorage (= 6.1.4.1) 161 | activesupport (= 6.1.4.1) 162 | bundler (>= 1.15.0) 163 | railties (= 6.1.4.1) 164 | sprockets-rails (>= 2.0.0) 165 | rails-dom-testing (2.0.3) 166 | activesupport (>= 4.2.0) 167 | nokogiri (>= 1.6) 168 | rails-html-sanitizer (1.4.2) 169 | loofah (~> 2.3) 170 | railties (6.1.4.1) 171 | actionpack (= 6.1.4.1) 172 | activesupport (= 6.1.4.1) 173 | method_source 174 | rake (>= 0.13) 175 | thor (~> 1.0) 176 | rainbow (3.0.0) 177 | rake (13.0.6) 178 | rb-fsevent (0.11.0) 179 | rb-inotify (0.10.1) 180 | ffi (~> 1.0) 181 | regexp_parser (2.1.1) 182 | rexml (3.2.5) 183 | rouge (3.26.0) 184 | rspec-core (3.10.1) 185 | rspec-support (~> 3.10.0) 186 | rspec-expectations (3.10.1) 187 | diff-lcs (>= 1.2.0, < 2.0) 188 | rspec-support (~> 3.10.0) 189 | rspec-mocks (3.10.2) 190 | diff-lcs (>= 1.2.0, < 2.0) 191 | rspec-support (~> 3.10.0) 192 | rspec-rails (5.0.2) 193 | actionpack (>= 5.2) 194 | activesupport (>= 5.2) 195 | railties (>= 5.2) 196 | rspec-core (~> 3.10) 197 | rspec-expectations (~> 3.10) 198 | rspec-mocks (~> 3.10) 199 | rspec-support (~> 3.10) 200 | rspec-support (3.10.2) 201 | rubocop (1.20.0) 202 | parallel (~> 1.10) 203 | parser (>= 3.0.0.0) 204 | rainbow (>= 2.2.2, < 4.0) 205 | regexp_parser (>= 1.8, < 3.0) 206 | rexml 207 | rubocop-ast (>= 1.9.1, < 2.0) 208 | ruby-progressbar (~> 1.7) 209 | unicode-display_width (>= 1.4.0, < 3.0) 210 | rubocop-ast (1.11.0) 211 | parser (>= 3.0.1.1) 212 | ruby-progressbar (1.11.0) 213 | sass (3.7.4) 214 | sass-listen (~> 4.0.0) 215 | sass-listen (4.0.0) 216 | rb-fsevent (~> 0.9, >= 0.9.4) 217 | rb-inotify (~> 0.9, >= 0.9.7) 218 | spring (2.1.1) 219 | spring-watcher-listen (2.0.1) 220 | listen (>= 2.7, < 4.0) 221 | spring (>= 1.2, < 3.0) 222 | sprockets (4.0.2) 223 | concurrent-ruby (~> 1.0) 224 | rack (> 1, < 3) 225 | sprockets-rails (3.2.2) 226 | actionpack (>= 4.0) 227 | activesupport (>= 4.0) 228 | sprockets (>= 3.0.0) 229 | thor (1.1.0) 230 | tzinfo (2.0.4) 231 | concurrent-ruby (~> 1.0) 232 | unicode-display_width (2.0.0) 233 | websocket-driver (0.7.5) 234 | websocket-extensions (>= 0.1.0) 235 | websocket-extensions (0.1.5) 236 | zeitwerk (2.4.2) 237 | 238 | PLATFORMS 239 | x86_64-darwin-20 240 | 241 | DEPENDENCIES 242 | acts-as-taggable-on 243 | bcrypt 244 | bootsnap 245 | byebug 246 | factory_bot_rails 247 | friendly_id 248 | graphiql-rails 249 | graphql 250 | graphql-batch 251 | graphql-docs 252 | graphql-rails_logger 253 | knock 254 | listen (>= 3.0.5, < 3.2) 255 | newrelic_rpm 256 | pg 257 | puma 258 | rack-cors 259 | rails 260 | rspec-rails 261 | rubocop 262 | spring 263 | spring-watcher-listen (~> 2.0.0) 264 | tzinfo-data 265 | 266 | RUBY VERSION 267 | ruby 3.0.2p107 268 | 269 | BUNDLED WITH 270 | 2.2.22 271 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: bin/rails server -p $PORT -e $RAILS_ENV 2 | release: rails db:migrate graphql:docs 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Ruby on Rails GraphQL Example App](logo.png) 2 | 3 | [![Build Status](https://travis-ci.com/dostu/rails-graphql-realworld-example-app.svg?branch=master)](https://travis-ci.com/dostu/rails-graphql-realworld-example-app) 4 | 5 | > ### Example Ruby on Rails GraphQL codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the [RealWorld GraphQL API spec](https://github.com/dostu/rails-graphql-realworld-example-app/blob/master/GRAPHQL_API_SPEC.md). 6 | 7 | This repo is functionality complete — PRs and issues welcome! 8 | 9 | You can also query the schema using [GraphiQL](https://realworld-graphql.herokuapp.com/graphiql). 10 | 11 | There is [React + Apollo frontend](https://github.com/dostu/react-apollo-realworld-example-app) implementation which can be used with this backend. 12 | 13 | ## Installation 14 | 15 | Make sure you have PostgreSQL installed. 16 | 17 | 1. Clone this repo 18 | 2. `bundle install` to install required dependencies 19 | 3. `rails db:reset` to create database, load schema and seed data 20 | 4. `rails s` to start the local server 21 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative 'config/application' 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/assets/config/manifest.js: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /app/channels/application_cable/channel.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Channel < ActionCable::Channel::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/channels/application_cable/connection.rb: -------------------------------------------------------------------------------- 1 | module ApplicationCable 2 | class Connection < ActionCable::Connection::Base 3 | end 4 | end 5 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | end 3 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/controllers/graphql_controller.rb: -------------------------------------------------------------------------------- 1 | class GraphqlController < ApplicationController 2 | include Knock::Authenticable 3 | 4 | def execute 5 | result = RealworldSchema.execute( 6 | params[:query], 7 | operation_name: params[:operationName], 8 | variables: ensure_hash(params[:variables]), 9 | context: context 10 | ) 11 | 12 | render json: result 13 | end 14 | 15 | private 16 | 17 | def context 18 | { current_user: current_user } 19 | end 20 | 21 | # Handle form data, JSON body, or a blank value 22 | def ensure_hash(ambiguous_param) 23 | case ambiguous_param 24 | when String 25 | if ambiguous_param.present? 26 | ensure_hash(JSON.parse(ambiguous_param)) 27 | else 28 | {} 29 | end 30 | when Hash, ActionController::Parameters 31 | ambiguous_param 32 | when nil 33 | {} 34 | else 35 | raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" 36 | end 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /app/controllers/user_token_controller.rb: -------------------------------------------------------------------------------- 1 | class UserTokenController < Knock::AuthTokenController 2 | end 3 | -------------------------------------------------------------------------------- /app/graphql/loaders/favorites_loader.rb: -------------------------------------------------------------------------------- 1 | class Loaders::FavoritesLoader < GraphQL::Batch::Loader 2 | def initialize(current_user) 3 | @current_user = current_user 4 | end 5 | 6 | def perform(ids) 7 | favorite_article_ids = @current_user.favorites.where(article_id: ids).pluck(:article_id) 8 | ids.each { |id| fulfill(id, favorite_article_ids.include?(id)) } 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/loaders/record_loader.rb: -------------------------------------------------------------------------------- 1 | class Loaders::RecordLoader < GraphQL::Batch::Loader 2 | def initialize(model) 3 | @model = model 4 | end 5 | 6 | def perform(ids) 7 | @model.where(id: ids).each { |record| fulfill(record.id, record) } 8 | ids.each { |id| fulfill(id, nil) unless fulfilled?(id) } 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/mutations/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/app/graphql/mutations/.keep -------------------------------------------------------------------------------- /app/graphql/mutations/add_comment.rb: -------------------------------------------------------------------------------- 1 | class Mutations::AddComment < Mutations::Base 2 | argument :article_id, ID, required: true 3 | argument :body, String, required: true 4 | 5 | field :comment, Types::CommentType, null: true 6 | field :errors, [Types::UserErrorType], null: false 7 | 8 | def resolve(article_id:, body:) 9 | current_user = context[:current_user] 10 | article = Article.find(article_id) 11 | 12 | comment = current_user.comments.create( 13 | article: article, 14 | body: body 15 | ) 16 | 17 | { 18 | errors: user_errors(comment.errors), 19 | comment: comment.valid? ? comment : nil 20 | } 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /app/graphql/mutations/base.rb: -------------------------------------------------------------------------------- 1 | class Mutations::Base < GraphQL::Schema::RelayClassicMutation 2 | def user_errors(errors) 3 | errors.full_messages.map { |error| UserError.new(error) } 4 | end 5 | 6 | def ensure_current_user 7 | current_user = context[:current_user] 8 | raise GraphQL::ExecutionError, 'Not authorized' unless current_user 9 | current_user 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /app/graphql/mutations/create_article.rb: -------------------------------------------------------------------------------- 1 | class Mutations::CreateArticle < Mutations::Base 2 | argument :title, String, required: true 3 | argument :description, String, required: true 4 | argument :body, String, required: true 5 | argument :tag_list, [String], required: true 6 | 7 | field :article, Types::ArticleType, null: true 8 | field :errors, [Types::UserErrorType], null: false 9 | 10 | def resolve(title:, description:, body:, tag_list:) 11 | current_user = ensure_current_user 12 | 13 | article = current_user.articles.create( 14 | title: title, 15 | description: description, 16 | body: body, 17 | tag_list: tag_list 18 | ) 19 | 20 | { 21 | errors: user_errors(article.errors), 22 | article: article.valid? ? article : nil 23 | } 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /app/graphql/mutations/create_user.rb: -------------------------------------------------------------------------------- 1 | class Mutations::CreateUser < Mutations::Base 2 | argument :username, String, required: true 3 | argument :email, String, required: true 4 | argument :password, String, required: true 5 | 6 | field :user, Types::UserType, null: true 7 | field :errors, [Types::UserErrorType], null: false 8 | 9 | def resolve(username:, email:, password:) 10 | user = User.create( 11 | username: username, 12 | email: email, 13 | password: password 14 | ) 15 | 16 | { 17 | errors: user_errors(user.errors), 18 | user: user.valid? ? user : nil 19 | } 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /app/graphql/mutations/delete_article.rb: -------------------------------------------------------------------------------- 1 | class Mutations::DeleteArticle < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :article, Types::ArticleType, null: false 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | article = current_user.articles.find(id) 9 | article.destroy! 10 | { article: article } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/delete_comment.rb: -------------------------------------------------------------------------------- 1 | class Mutations::DeleteComment < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :comment, Types::CommentType, null: true 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | comment = current_user.comments.find(id) 9 | comment.destroy! 10 | { comment: comment } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/favorite_article.rb: -------------------------------------------------------------------------------- 1 | class Mutations::FavoriteArticle < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :article, Types::ArticleType, null: true 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | article = Article.find(id) 9 | current_user.favorite_articles << article 10 | { article: article.reload } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/follow_user.rb: -------------------------------------------------------------------------------- 1 | class Mutations::FollowUser < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :user, Types::UserType, null: true 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | followee = User.find(id) 9 | current_user.followees << followee 10 | { user: followee.reload } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/sign_in_user.rb: -------------------------------------------------------------------------------- 1 | class Mutations::SignInUser < Mutations::Base 2 | argument :email, String, required: true 3 | argument :password, String, required: true 4 | 5 | field :token, String, null: true 6 | field :viewer, Types::ViewerType, null: true 7 | field :errors, [Types::UserErrorType], null: false 8 | 9 | def resolve(email:, password:) 10 | user = authenticate_user(email, password) 11 | 12 | unless user 13 | return { 14 | errors: [UserError.new('email or password is invalid')] 15 | } 16 | end 17 | 18 | token = Knock::AuthToken.new(payload: { sub: user.id }).token 19 | 20 | { 21 | viewer: user, 22 | token: token, 23 | errors: [] 24 | } 25 | end 26 | 27 | private 28 | 29 | def authenticate_user(email, password) 30 | return if email.blank? || password.blank? 31 | 32 | user = User.find_by(email: email) 33 | return unless user 34 | return unless user.authenticate(password) 35 | 36 | user 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /app/graphql/mutations/unfavorite_article.rb: -------------------------------------------------------------------------------- 1 | class Mutations::UnfavoriteArticle < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :article, Types::ArticleType, null: true 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | article = Article.find(id) 9 | current_user.favorite_articles.destroy(article) 10 | { article: article.reload } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/unfollow_user.rb: -------------------------------------------------------------------------------- 1 | class Mutations::UnfollowUser < Mutations::Base 2 | argument :id, ID, required: true 3 | 4 | field :user, Types::UserType, null: true 5 | 6 | def resolve(id:) 7 | current_user = ensure_current_user 8 | followee = User.find(id) 9 | current_user.followees.destroy(followee) 10 | { user: followee.reload } 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /app/graphql/mutations/update_article.rb: -------------------------------------------------------------------------------- 1 | class Mutations::UpdateArticle < Mutations::Base 2 | argument :id, ID, required: true 3 | argument :title, String, required: true 4 | argument :description, String, required: true 5 | argument :body, String, required: true 6 | argument :tag_list, [String], required: true 7 | 8 | field :article, Types::ArticleType, null: true 9 | field :errors, [Types::UserErrorType], null: false 10 | 11 | def resolve(id:, title:, description:, body:, tag_list:) 12 | current_user = ensure_current_user 13 | article = current_user.articles.find(id) 14 | 15 | article.update( 16 | title: title, 17 | description: description, 18 | body: body, 19 | tag_list: tag_list 20 | ) 21 | 22 | { 23 | errors: user_errors(article.errors), 24 | article: article.reload 25 | } 26 | end 27 | end 28 | -------------------------------------------------------------------------------- /app/graphql/mutations/update_user.rb: -------------------------------------------------------------------------------- 1 | class Mutations::UpdateUser < Mutations::Base 2 | argument :email, String, required: true 3 | argument :username, String, required: true 4 | argument :bio, String, required: false 5 | argument :image, String, required: false 6 | argument :password, String, required: false 7 | 8 | field :user, Types::UserType, null: true 9 | field :errors, [Types::UserErrorType], null: false 10 | 11 | def resolve(email:, username:, bio: nil, image: nil, password: nil) 12 | current_user = ensure_current_user 13 | 14 | current_user.assign_attributes( 15 | email: email, 16 | username: username, 17 | bio: bio, 18 | image: image 19 | ) 20 | 21 | current_user.password = password if password.present? 22 | 23 | current_user.save 24 | 25 | { 26 | errors: user_errors(current_user.errors), 27 | user: current_user.reload 28 | } 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /app/graphql/realworld_schema.rb: -------------------------------------------------------------------------------- 1 | class RealworldSchema < GraphQL::Schema 2 | use GraphQL::Batch 3 | use GraphQL::Tracing::NewRelicTracing, set_transaction_name: true 4 | 5 | mutation(Types::MutationType) 6 | query(Types::QueryType) 7 | 8 | max_complexity 200 9 | max_depth 10 10 | end 11 | -------------------------------------------------------------------------------- /app/graphql/schema.graphql: -------------------------------------------------------------------------------- 1 | """ 2 | Autogenerated input type of AddComment 3 | """ 4 | input AddCommentInput { 5 | articleId: ID! 6 | body: String! 7 | 8 | """ 9 | A unique identifier for the client performing the mutation. 10 | """ 11 | clientMutationId: String 12 | } 13 | 14 | """ 15 | Autogenerated return type of AddComment 16 | """ 17 | type AddCommentPayload { 18 | """ 19 | A unique identifier for the client performing the mutation. 20 | """ 21 | clientMutationId: String 22 | comment: Comment 23 | errors: [UserError!]! 24 | } 25 | 26 | type Article { 27 | author: User 28 | body: String! 29 | comments: [Comment!]! 30 | createdAt: ISO8601DateTime! 31 | description: String! 32 | favoritesCount: Int! 33 | id: ID! 34 | slug: String! 35 | tagList: [String!]! 36 | title: String! 37 | updatedAt: ISO8601DateTime! 38 | viewerHasFavorited: Boolean! 39 | } 40 | 41 | """ 42 | The connection type for Article. 43 | """ 44 | type ArticleConnection { 45 | """ 46 | A list of edges. 47 | """ 48 | edges: [ArticleEdge] 49 | 50 | """ 51 | A list of nodes. 52 | """ 53 | nodes: [Article] 54 | 55 | """ 56 | Information to aid in pagination. 57 | """ 58 | pageInfo: PageInfo! 59 | } 60 | 61 | """ 62 | An edge in a connection. 63 | """ 64 | type ArticleEdge { 65 | """ 66 | A cursor for use in pagination. 67 | """ 68 | cursor: String! 69 | 70 | """ 71 | The item at the end of the edge. 72 | """ 73 | node: Article 74 | } 75 | 76 | type Comment { 77 | article: Article 78 | author: User 79 | body: String! 80 | createdAt: ISO8601DateTime! 81 | id: ID! 82 | updatedAt: ISO8601DateTime! 83 | } 84 | 85 | """ 86 | Autogenerated input type of CreateArticle 87 | """ 88 | input CreateArticleInput { 89 | body: String! 90 | 91 | """ 92 | A unique identifier for the client performing the mutation. 93 | """ 94 | clientMutationId: String 95 | description: String! 96 | tagList: [String!]! 97 | title: String! 98 | } 99 | 100 | """ 101 | Autogenerated return type of CreateArticle 102 | """ 103 | type CreateArticlePayload { 104 | article: Article 105 | 106 | """ 107 | A unique identifier for the client performing the mutation. 108 | """ 109 | clientMutationId: String 110 | errors: [UserError!]! 111 | } 112 | 113 | """ 114 | Autogenerated input type of CreateUser 115 | """ 116 | input CreateUserInput { 117 | """ 118 | A unique identifier for the client performing the mutation. 119 | """ 120 | clientMutationId: String 121 | email: String! 122 | password: String! 123 | username: String! 124 | } 125 | 126 | """ 127 | Autogenerated return type of CreateUser 128 | """ 129 | type CreateUserPayload { 130 | """ 131 | A unique identifier for the client performing the mutation. 132 | """ 133 | clientMutationId: String 134 | errors: [UserError!]! 135 | user: User 136 | } 137 | 138 | """ 139 | Autogenerated input type of DeleteArticle 140 | """ 141 | input DeleteArticleInput { 142 | """ 143 | A unique identifier for the client performing the mutation. 144 | """ 145 | clientMutationId: String 146 | id: ID! 147 | } 148 | 149 | """ 150 | Autogenerated return type of DeleteArticle 151 | """ 152 | type DeleteArticlePayload { 153 | article: Article! 154 | 155 | """ 156 | A unique identifier for the client performing the mutation. 157 | """ 158 | clientMutationId: String 159 | } 160 | 161 | """ 162 | Autogenerated input type of DeleteComment 163 | """ 164 | input DeleteCommentInput { 165 | """ 166 | A unique identifier for the client performing the mutation. 167 | """ 168 | clientMutationId: String 169 | id: ID! 170 | } 171 | 172 | """ 173 | Autogenerated return type of DeleteComment 174 | """ 175 | type DeleteCommentPayload { 176 | """ 177 | A unique identifier for the client performing the mutation. 178 | """ 179 | clientMutationId: String 180 | comment: Comment 181 | } 182 | 183 | """ 184 | Autogenerated input type of FavoriteArticle 185 | """ 186 | input FavoriteArticleInput { 187 | """ 188 | A unique identifier for the client performing the mutation. 189 | """ 190 | clientMutationId: String 191 | id: ID! 192 | } 193 | 194 | """ 195 | Autogenerated return type of FavoriteArticle 196 | """ 197 | type FavoriteArticlePayload { 198 | article: Article 199 | 200 | """ 201 | A unique identifier for the client performing the mutation. 202 | """ 203 | clientMutationId: String 204 | } 205 | 206 | """ 207 | Autogenerated input type of FollowUser 208 | """ 209 | input FollowUserInput { 210 | """ 211 | A unique identifier for the client performing the mutation. 212 | """ 213 | clientMutationId: String 214 | id: ID! 215 | } 216 | 217 | """ 218 | Autogenerated return type of FollowUser 219 | """ 220 | type FollowUserPayload { 221 | """ 222 | A unique identifier for the client performing the mutation. 223 | """ 224 | clientMutationId: String 225 | user: User 226 | } 227 | 228 | """ 229 | The connection type for User. 230 | """ 231 | type FollowersConnection { 232 | """ 233 | A list of edges. 234 | """ 235 | edges: [UserEdge] 236 | 237 | """ 238 | A list of nodes. 239 | """ 240 | nodes: [User] 241 | 242 | """ 243 | Information to aid in pagination. 244 | """ 245 | pageInfo: PageInfo! 246 | totalCount: Int! 247 | } 248 | 249 | """ 250 | An ISO 8601-encoded datetime 251 | """ 252 | scalar ISO8601DateTime 253 | 254 | type Mutation { 255 | addComment( 256 | """ 257 | Parameters for AddComment 258 | """ 259 | input: AddCommentInput! 260 | ): AddCommentPayload 261 | createArticle( 262 | """ 263 | Parameters for CreateArticle 264 | """ 265 | input: CreateArticleInput! 266 | ): CreateArticlePayload 267 | createUser( 268 | """ 269 | Parameters for CreateUser 270 | """ 271 | input: CreateUserInput! 272 | ): CreateUserPayload 273 | deleteArticle( 274 | """ 275 | Parameters for DeleteArticle 276 | """ 277 | input: DeleteArticleInput! 278 | ): DeleteArticlePayload 279 | deleteComment( 280 | """ 281 | Parameters for DeleteComment 282 | """ 283 | input: DeleteCommentInput! 284 | ): DeleteCommentPayload 285 | favoriteArticle( 286 | """ 287 | Parameters for FavoriteArticle 288 | """ 289 | input: FavoriteArticleInput! 290 | ): FavoriteArticlePayload 291 | followUser( 292 | """ 293 | Parameters for FollowUser 294 | """ 295 | input: FollowUserInput! 296 | ): FollowUserPayload 297 | signInUser( 298 | """ 299 | Parameters for SignInUser 300 | """ 301 | input: SignInUserInput! 302 | ): SignInUserPayload 303 | unfavoriteArticle( 304 | """ 305 | Parameters for UnfavoriteArticle 306 | """ 307 | input: UnfavoriteArticleInput! 308 | ): UnfavoriteArticlePayload 309 | unfollowUser( 310 | """ 311 | Parameters for UnfollowUser 312 | """ 313 | input: UnfollowUserInput! 314 | ): UnfollowUserPayload 315 | updateArticle( 316 | """ 317 | Parameters for UpdateArticle 318 | """ 319 | input: UpdateArticleInput! 320 | ): UpdateArticlePayload 321 | updateUser( 322 | """ 323 | Parameters for UpdateUser 324 | """ 325 | input: UpdateUserInput! 326 | ): UpdateUserPayload 327 | } 328 | 329 | """ 330 | Information about pagination in a connection. 331 | """ 332 | type PageInfo { 333 | """ 334 | When paginating forwards, the cursor to continue. 335 | """ 336 | endCursor: String 337 | 338 | """ 339 | When paginating forwards, are there more items? 340 | """ 341 | hasNextPage: Boolean! 342 | 343 | """ 344 | When paginating backwards, are there more items? 345 | """ 346 | hasPreviousPage: Boolean! 347 | 348 | """ 349 | When paginating backwards, the cursor to continue. 350 | """ 351 | startCursor: String 352 | } 353 | 354 | type Query { 355 | article(slug: String!): Article 356 | articles( 357 | """ 358 | Returns the elements in the list that come after the specified cursor. 359 | """ 360 | after: String 361 | 362 | """ 363 | Returns the elements in the list that come before the specified cursor. 364 | """ 365 | before: String 366 | 367 | """ 368 | Returns the first _n_ elements from the list. 369 | """ 370 | first: Int 371 | 372 | """ 373 | Returns the last _n_ elements from the list. 374 | """ 375 | last: Int 376 | tag: String 377 | ): ArticleConnection! 378 | tags: [String!]! 379 | user(username: String!): User 380 | viewer: Viewer 381 | } 382 | 383 | """ 384 | Autogenerated input type of SignInUser 385 | """ 386 | input SignInUserInput { 387 | """ 388 | A unique identifier for the client performing the mutation. 389 | """ 390 | clientMutationId: String 391 | email: String! 392 | password: String! 393 | } 394 | 395 | """ 396 | Autogenerated return type of SignInUser 397 | """ 398 | type SignInUserPayload { 399 | """ 400 | A unique identifier for the client performing the mutation. 401 | """ 402 | clientMutationId: String 403 | errors: [UserError!]! 404 | token: String 405 | viewer: Viewer 406 | } 407 | 408 | """ 409 | Autogenerated input type of UnfavoriteArticle 410 | """ 411 | input UnfavoriteArticleInput { 412 | """ 413 | A unique identifier for the client performing the mutation. 414 | """ 415 | clientMutationId: String 416 | id: ID! 417 | } 418 | 419 | """ 420 | Autogenerated return type of UnfavoriteArticle 421 | """ 422 | type UnfavoriteArticlePayload { 423 | article: Article 424 | 425 | """ 426 | A unique identifier for the client performing the mutation. 427 | """ 428 | clientMutationId: String 429 | } 430 | 431 | """ 432 | Autogenerated input type of UnfollowUser 433 | """ 434 | input UnfollowUserInput { 435 | """ 436 | A unique identifier for the client performing the mutation. 437 | """ 438 | clientMutationId: String 439 | id: ID! 440 | } 441 | 442 | """ 443 | Autogenerated return type of UnfollowUser 444 | """ 445 | type UnfollowUserPayload { 446 | """ 447 | A unique identifier for the client performing the mutation. 448 | """ 449 | clientMutationId: String 450 | user: User 451 | } 452 | 453 | """ 454 | Autogenerated input type of UpdateArticle 455 | """ 456 | input UpdateArticleInput { 457 | body: String! 458 | 459 | """ 460 | A unique identifier for the client performing the mutation. 461 | """ 462 | clientMutationId: String 463 | description: String! 464 | id: ID! 465 | tagList: [String!]! 466 | title: String! 467 | } 468 | 469 | """ 470 | Autogenerated return type of UpdateArticle 471 | """ 472 | type UpdateArticlePayload { 473 | article: Article 474 | 475 | """ 476 | A unique identifier for the client performing the mutation. 477 | """ 478 | clientMutationId: String 479 | errors: [UserError!]! 480 | } 481 | 482 | """ 483 | Autogenerated input type of UpdateUser 484 | """ 485 | input UpdateUserInput { 486 | bio: String 487 | 488 | """ 489 | A unique identifier for the client performing the mutation. 490 | """ 491 | clientMutationId: String 492 | email: String! 493 | image: String 494 | password: String 495 | username: String! 496 | } 497 | 498 | """ 499 | Autogenerated return type of UpdateUser 500 | """ 501 | type UpdateUserPayload { 502 | """ 503 | A unique identifier for the client performing the mutation. 504 | """ 505 | clientMutationId: String 506 | errors: [UserError!]! 507 | user: User 508 | } 509 | 510 | type User { 511 | articles( 512 | """ 513 | Returns the elements in the list that come after the specified cursor. 514 | """ 515 | after: String 516 | 517 | """ 518 | Returns the elements in the list that come before the specified cursor. 519 | """ 520 | before: String 521 | 522 | """ 523 | Returns the first _n_ elements from the list. 524 | """ 525 | first: Int 526 | 527 | """ 528 | Returns the last _n_ elements from the list. 529 | """ 530 | last: Int 531 | ): ArticleConnection! 532 | bio: String 533 | email: String! 534 | favoriteArticles( 535 | """ 536 | Returns the elements in the list that come after the specified cursor. 537 | """ 538 | after: String 539 | 540 | """ 541 | Returns the elements in the list that come before the specified cursor. 542 | """ 543 | before: String 544 | 545 | """ 546 | Returns the first _n_ elements from the list. 547 | """ 548 | first: Int 549 | 550 | """ 551 | Returns the last _n_ elements from the list. 552 | """ 553 | last: Int 554 | ): ArticleConnection! 555 | followedByViewer: Boolean! 556 | followers( 557 | """ 558 | Returns the elements in the list that come after the specified cursor. 559 | """ 560 | after: String 561 | 562 | """ 563 | Returns the elements in the list that come before the specified cursor. 564 | """ 565 | before: String 566 | 567 | """ 568 | Returns the first _n_ elements from the list. 569 | """ 570 | first: Int 571 | 572 | """ 573 | Returns the last _n_ elements from the list. 574 | """ 575 | last: Int 576 | ): FollowersConnection! 577 | id: ID! 578 | image: String 579 | username: String! 580 | } 581 | 582 | """ 583 | An edge in a connection. 584 | """ 585 | type UserEdge { 586 | """ 587 | A cursor for use in pagination. 588 | """ 589 | cursor: String! 590 | 591 | """ 592 | The item at the end of the edge. 593 | """ 594 | node: User 595 | } 596 | 597 | type UserError { 598 | message: String! 599 | path: String 600 | } 601 | 602 | type Viewer { 603 | feed( 604 | """ 605 | Returns the elements in the list that come after the specified cursor. 606 | """ 607 | after: String 608 | 609 | """ 610 | Returns the elements in the list that come before the specified cursor. 611 | """ 612 | before: String 613 | 614 | """ 615 | Returns the first _n_ elements from the list. 616 | """ 617 | first: Int 618 | 619 | """ 620 | Returns the last _n_ elements from the list. 621 | """ 622 | last: Int 623 | ): ArticleConnection! 624 | user: User! 625 | } 626 | -------------------------------------------------------------------------------- /app/graphql/types/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/app/graphql/types/.keep -------------------------------------------------------------------------------- /app/graphql/types/article_type.rb: -------------------------------------------------------------------------------- 1 | class Types::ArticleType < GraphQL::Schema::Object 2 | graphql_name 'Article' 3 | 4 | field :id, ID, null: false 5 | field :slug, String, null: false, method: :friendly_id 6 | field :title, String, null: false 7 | field :description, String, null: false 8 | field :body, String, null: false 9 | field :tag_list, [String], null: false 10 | field :created_at, GraphQL::Types::ISO8601DateTime, null: false 11 | field :updated_at, GraphQL::Types::ISO8601DateTime, null: false 12 | field :viewer_has_favorited, Boolean, null: false 13 | field :favorites_count, Int, null: false 14 | field :author, Types::UserType, null: true 15 | field :comments, [Types::CommentType], null: false 16 | 17 | def viewer_has_favorited 18 | current_user = context[:current_user] 19 | return false unless current_user 20 | Loaders::FavoritesLoader.for(current_user).load(object.id) 21 | end 22 | 23 | def author 24 | Loaders::RecordLoader.for(User).load(object.author_id) 25 | end 26 | 27 | def comments 28 | object.comments.order(id: :desc) 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /app/graphql/types/comment_type.rb: -------------------------------------------------------------------------------- 1 | class Types::CommentType < GraphQL::Schema::Object 2 | graphql_name 'Comment' 3 | 4 | field :id, ID, null: false 5 | field :created_at, GraphQL::Types::ISO8601DateTime, null: false 6 | field :updated_at, GraphQL::Types::ISO8601DateTime, null: false 7 | field :body, String, null: false 8 | field :author, Types::UserType, null: true 9 | field :article, Types::ArticleType, null: true 10 | 11 | def author 12 | Loaders::RecordLoader.for(User).load(object.author_id) 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /app/graphql/types/followers_connection_type.rb: -------------------------------------------------------------------------------- 1 | class Types::FollowersConnectionType < GraphQL::Types::Relay::BaseConnection 2 | edge_type(Types::UserEdgeType) 3 | 4 | field :total_count, Integer, null: false 5 | def total_count 6 | object.nodes.size 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/graphql/types/mutation_type.rb: -------------------------------------------------------------------------------- 1 | class Types::MutationType < GraphQL::Schema::Object 2 | field :createUser, mutation: Mutations::CreateUser 3 | field :updateUser, mutation: Mutations::UpdateUser 4 | field :signInUser, mutation: Mutations::SignInUser 5 | field :followUser, mutation: Mutations::FollowUser 6 | field :unfollowUser, mutation: Mutations::UnfollowUser 7 | 8 | field :createArticle, mutation: Mutations::CreateArticle 9 | field :updateArticle, mutation: Mutations::UpdateArticle 10 | field :deleteArticle, mutation: Mutations::DeleteArticle 11 | field :favoriteArticle, mutation: Mutations::FavoriteArticle 12 | field :unfavoriteArticle, mutation: Mutations::UnfavoriteArticle 13 | 14 | field :addComment, mutation: Mutations::AddComment 15 | field :deleteComment, mutation: Mutations::DeleteComment 16 | end 17 | -------------------------------------------------------------------------------- /app/graphql/types/query_type.rb: -------------------------------------------------------------------------------- 1 | class Types::QueryType < GraphQL::Schema::Object 2 | field :viewer, Types::ViewerType, null: true 3 | def viewer 4 | context[:current_user] 5 | end 6 | 7 | field :user, Types::UserType, null: true do 8 | argument :username, String, required: true 9 | end 10 | def user(username:) 11 | User.find_by(username: username) 12 | end 13 | 14 | field :articles, Types::ArticleType.connection_type, null: false do 15 | argument :tag, String, required: false 16 | end 17 | def articles(tag: nil, authored_by: nil, favorited_by: nil) 18 | articles = Article.all 19 | 20 | if tag.present? 21 | articles = articles.tagged_with(tag) 22 | end 23 | 24 | articles.order(id: :desc) 25 | end 26 | 27 | field :article, Types::ArticleType, null: true do 28 | argument :slug, String, required: true 29 | end 30 | def article(slug:) 31 | Article.friendly.find(slug) 32 | end 33 | 34 | field :tags, [String], null: false 35 | def tags 36 | ActsAsTaggableOn::Tag.most_used.pluck(:name) 37 | end 38 | end 39 | -------------------------------------------------------------------------------- /app/graphql/types/user_edge_type.rb: -------------------------------------------------------------------------------- 1 | class Types::UserEdgeType < GraphQL::Types::Relay::BaseEdge 2 | node_type(Types::UserType) 3 | end 4 | -------------------------------------------------------------------------------- /app/graphql/types/user_error_type.rb: -------------------------------------------------------------------------------- 1 | class Types::UserErrorType < GraphQL::Schema::Object 2 | graphql_name 'UserError' 3 | 4 | field :message, String, null: false 5 | field :path, String, null: true 6 | end 7 | -------------------------------------------------------------------------------- /app/graphql/types/user_type.rb: -------------------------------------------------------------------------------- 1 | class Types::UserType < GraphQL::Schema::Object 2 | graphql_name 'User' 3 | 4 | field :id, ID, null: false 5 | field :username, String, null: false 6 | field :email, String, null: false 7 | field :image, String, null: true 8 | field :bio, String, null: true 9 | field :followed_by_viewer, Boolean, null: false 10 | field :followers, Types::FollowersConnectionType, null: false, connection: true 11 | field :articles, Types::ArticleType.connection_type, null: false 12 | field :favorite_articles, Types::ArticleType.connection_type, null: false 13 | 14 | def followed_by_viewer 15 | current_user = context[:current_user] 16 | return false unless current_user 17 | current_user.followees.exists?(object.id) 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /app/graphql/types/viewer_type.rb: -------------------------------------------------------------------------------- 1 | class Types::ViewerType < GraphQL::Schema::Object 2 | graphql_name 'Viewer' 3 | 4 | field :user, Types::UserType, null: false 5 | def user 6 | object 7 | end 8 | 9 | field :feed, Types::ArticleType.connection_type, null: false 10 | def feed 11 | Article.where(author: object.followees).order(id: :desc) 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /app/graphql/user_error.rb: -------------------------------------------------------------------------------- 1 | UserError = Struct.new(:message, :path) 2 | -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | end 3 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/article.rb: -------------------------------------------------------------------------------- 1 | class Article < ApplicationRecord 2 | extend FriendlyId 3 | friendly_id :title, use: :slugged 4 | acts_as_taggable 5 | 6 | belongs_to :author, class_name: 'User' 7 | has_many :comments, dependent: :destroy 8 | has_many :favorites, dependent: :destroy 9 | 10 | validates :title, :description, :body, presence: true 11 | end 12 | -------------------------------------------------------------------------------- /app/models/comment.rb: -------------------------------------------------------------------------------- 1 | class Comment < ApplicationRecord 2 | belongs_to :author, class_name: 'User' 3 | belongs_to :article 4 | 5 | validates :body, presence: true 6 | end 7 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/favorite.rb: -------------------------------------------------------------------------------- 1 | class Favorite < ApplicationRecord 2 | belongs_to :user 3 | belongs_to :article, counter_cache: true 4 | 5 | validates :article, uniqueness: { scope: :user } 6 | end 7 | -------------------------------------------------------------------------------- /app/models/follow.rb: -------------------------------------------------------------------------------- 1 | class Follow < ApplicationRecord 2 | belongs_to :follower, class_name: 'User' 3 | belongs_to :followee, class_name: 'User', counter_cache: true 4 | 5 | validates :followee, uniqueness: { scope: :follower } 6 | end 7 | -------------------------------------------------------------------------------- /app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ApplicationRecord 2 | has_secure_password 3 | 4 | validates :username, presence: true 5 | validates :email, presence: true, uniqueness: true 6 | 7 | has_many :articles, foreign_key: :author_id, dependent: :destroy, inverse_of: :author 8 | has_many :comments, foreign_key: :author_id, dependent: :destroy, inverse_of: :author 9 | has_many :favorites, dependent: :destroy 10 | has_many :favorite_articles, class_name: 'Article', through: :favorites, source: :article 11 | has_many :follows, foreign_key: :follower_id, dependent: :destroy, inverse_of: :follower 12 | has_many :followees, class_name: 'User', through: :follows 13 | has_many :followers, class_name: 'User', through: :follows 14 | end 15 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 || ">= 0.a" 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../../Gemfile", __FILE__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_version 64 | @bundler_version ||= begin 65 | env_var_version || cli_arg_version || 66 | lockfile_version || "#{Gem::Requirement.default}.a" 67 | end 68 | end 69 | 70 | def load_bundler! 71 | ENV["BUNDLE_GEMFILE"] ||= gemfile 72 | 73 | # must dup string for RG < 1.8 compatibility 74 | activate_bundler(bundler_version.dup) 75 | end 76 | 77 | def activate_bundler(bundler_version) 78 | if Gem::Version.correct?(bundler_version) && Gem::Version.new(bundler_version).release < Gem::Version.new("2.0") 79 | bundler_version = "< 2" 80 | end 81 | gem_error = activation_error_handling do 82 | gem "bundler", bundler_version 83 | end 84 | return if gem_error.nil? 85 | require_error = activation_error_handling do 86 | require "bundler/version" 87 | end 88 | return if require_error.nil? && Gem::Requirement.new(bundler_version).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 89 | warn "Activating bundler (#{bundler_version}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_version}'`" 90 | exit 42 91 | end 92 | 93 | def activation_error_handling 94 | yield 95 | nil 96 | rescue StandardError, LoadError => e 97 | e 98 | end 99 | end 100 | 101 | m.load_bundler! 102 | 103 | if m.invoked_as_script? 104 | load Gem.bin_path("bundler", "bundle") 105 | end 106 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../config/application', __dir__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /bin/rspec: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'rspec' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "pathname" 12 | ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile", 13 | Pathname.new(__FILE__).realpath) 14 | 15 | bundle_binstub = File.expand_path("../bundle", __FILE__) 16 | 17 | if File.file?(bundle_binstub) 18 | if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/ 19 | load(bundle_binstub) 20 | else 21 | abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. 22 | Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") 23 | end 24 | end 25 | 26 | require "rubygems" 27 | require "bundler/setup" 28 | 29 | load Gem.bin_path("rspec-core", "rspec") 30 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a starting point to setup your application. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:setup' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /bin/update: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'fileutils' 3 | include FileUtils 4 | 5 | # path to your application root. 6 | APP_ROOT = File.expand_path('..', __dir__) 7 | 8 | def system!(*args) 9 | system(*args) || abort("\n== Command #{args} failed ==") 10 | end 11 | 12 | chdir APP_ROOT do 13 | # This script is a way to update your development environment automatically. 14 | # Add necessary update steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | puts "\n== Updating database ==" 21 | system! 'bin/rails db:migrate' 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system! 'bin/rails log:clear tmp:clear' 25 | 26 | puts "\n== Restarting application server ==" 27 | system! 'bin/rails restart' 28 | end 29 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative 'config/environment' 4 | 5 | run Rails.application 6 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative 'boot' 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | require "action_view/railtie" 12 | require "action_cable/engine" 13 | require "sprockets/railtie" 14 | require "rails/test_unit/railtie" 15 | 16 | # Require the gems listed in Gemfile, including any gems 17 | # you've limited to :test, :development, or :production. 18 | Bundler.require(*Rails.groups) 19 | 20 | module Realworld 21 | class Application < Rails::Application 22 | # Initialize configuration defaults for originally generated Rails version. 23 | config.load_defaults 5.2 24 | 25 | # Settings in config/environments/* take precedence over those specified here. 26 | # Application configuration can go into files in config/initializers 27 | # -- all .rb files in that directory are automatically loaded after loading 28 | # the framework and any gems in your application. 29 | 30 | # Only loads a smaller set of middleware suitable for API only apps. 31 | # Middleware like session, flash, cookies can be added back manually. 32 | # Skip views, helpers and assets when generating a new resource. 33 | config.api_only = true 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | require 'bootsnap/setup' # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/cable.yml: -------------------------------------------------------------------------------- 1 | development: 2 | adapter: async 3 | 4 | test: 5 | adapter: async 6 | 7 | production: 8 | adapter: redis 9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> 10 | channel_prefix: realworld_production 11 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | UE9gdo1aFdE/5Cnvzf65v+ez25NQ4sViaV73EpxrRnvZoVoQVppqRFAKlkH2gv5bHXwYvp1hS7t7245CsdEytKoM7d1yLmTLzgwEJR2VF4Qb2uaaVbB1ik4ckfVIWLTC4O2PKDnS7bPLwosw0iShSuSgJ7w+T8pde4ZGcX9rQXYit75g/frIzd3/UWeM3BqahkoiR74SeOfLgIbjLT24+KVI2199XYBCdyY3ucvJhjpaSOltrBGaG/iC0mKIRsSzyrXqQw6fmcLNXZ5eTLY0foyTVNE3gMe6wLjLLmT4zc0S0F8KpAmnbkofJ+1JaueJrpq8Zicbc3v654OGh/05Caj5akl9BoOJetHGtGntPmYOSS+W5taiXYf+rwLVAzfB/R3buB5iVnEC5qR9koYiKa+N2dgg7Hm6u4OZ--AQkozop0MqRFrDgy--/FjJ0XraDG9w2kCytk0RFg== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.1 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On OS X with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On OS X with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see Rails configuration guide 21 | # http://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: realworld_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user that initialized the database. 32 | #username: rails-postgres 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: realworld_test 61 | 62 | # As with config/secrets.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password as a unix environment variable when you boot 67 | # the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database 68 | # for a full rundown on how to provide these environment variables in a 69 | # production deployment. 70 | # 71 | # On Heroku and other platform providers, you may have a full connection URL 72 | # available as an environment variable. For example: 73 | # 74 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 75 | # 76 | # You can use this database configuration with: 77 | # 78 | # production: 79 | # url: <%= ENV['DATABASE_URL'] %> 80 | # 81 | production: 82 | <<: *default 83 | database: realworld_production 84 | username: realworld 85 | password: <%= ENV['RAILS-POSTGRES_DATABASE_PASSWORD'] %> 86 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative 'application' 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports. 13 | config.consider_all_requests_local = true 14 | 15 | # Enable/disable caching. By default caching is disabled. 16 | # Run rails dev:cache to toggle caching. 17 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 18 | config.action_controller.perform_caching = true 19 | 20 | config.cache_store = :memory_store 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 23 | } 24 | else 25 | config.action_controller.perform_caching = false 26 | 27 | config.cache_store = :null_store 28 | end 29 | 30 | # Store uploaded files on the local file system (see config/storage.yml for options) 31 | config.active_storage.service = :local 32 | 33 | # Don't care if the mailer can't send. 34 | config.action_mailer.raise_delivery_errors = false 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Print deprecation notices to the Rails logger. 39 | config.active_support.deprecation = :log 40 | 41 | # Raise an error on page load if there are pending migrations. 42 | config.active_record.migration_error = :page_load 43 | 44 | # Highlight code that triggered database queries in logs. 45 | config.active_record.verbose_query_logs = true 46 | 47 | 48 | # Raises error for missing translations 49 | # config.action_view.raise_on_missing_translations = true 50 | 51 | # Use an evented file watcher to asynchronously detect changes in source code, 52 | # routes, locales, etc. This feature depends on the listen gem. 53 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 54 | end 55 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 18 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 19 | # config.require_master_key = true 20 | 21 | # Disable serving static files from the `/public` folder by default since 22 | # Apache or NGINX already handles this. 23 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 24 | 25 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 26 | # config.action_controller.asset_host = 'http://assets.example.com' 27 | 28 | # Specifies the header that your server uses for sending files. 29 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 30 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 31 | 32 | # Store uploaded files on the local file system (see config/storage.yml for options) 33 | config.active_storage.service = :local 34 | 35 | # Mount Action Cable outside main process or domain 36 | # config.action_cable.mount_path = nil 37 | # config.action_cable.url = 'wss://example.com/cable' 38 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] 39 | 40 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 41 | # config.force_ssl = true 42 | 43 | # Use the lowest log level to ensure availability of diagnostic information 44 | # when problems arise. 45 | config.log_level = :debug 46 | 47 | # Prepend all log lines with the following tags. 48 | config.log_tags = [ :request_id ] 49 | 50 | # Use a different cache store in production. 51 | # config.cache_store = :mem_cache_store 52 | 53 | # Use a real queuing backend for Active Job (and separate queues per environment) 54 | # config.active_job.queue_adapter = :resque 55 | # config.active_job.queue_name_prefix = "realworld_#{Rails.env}" 56 | 57 | config.action_mailer.perform_caching = false 58 | 59 | # Ignore bad email addresses and do not raise email delivery errors. 60 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 61 | # config.action_mailer.raise_delivery_errors = false 62 | 63 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 64 | # the I18n.default_locale when a translation cannot be found). 65 | config.i18n.fallbacks = true 66 | 67 | # Send deprecation notices to registered listeners. 68 | config.active_support.deprecation = :notify 69 | 70 | # Use default logging formatter so that PID and timestamp are not suppressed. 71 | config.log_formatter = ::Logger::Formatter.new 72 | 73 | # Use a different logger for distributed setups. 74 | # require 'syslog/logger' 75 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 76 | 77 | if ENV["RAILS_LOG_TO_STDOUT"].present? 78 | logger = ActiveSupport::Logger.new(STDOUT) 79 | logger.formatter = config.log_formatter 80 | config.logger = ActiveSupport::TaggedLogging.new(logger) 81 | end 82 | 83 | # Do not dump schema after migrations. 84 | config.active_record.dump_schema_after_migration = false 85 | end 86 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Rails.application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure public file server for tests with Cache-Control for performance. 16 | config.public_file_server.enabled = true 17 | config.public_file_server.headers = { 18 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 19 | } 20 | 21 | # Show full error reports and disable caching. 22 | config.consider_all_requests_local = true 23 | config.action_controller.perform_caching = false 24 | 25 | # Raise exceptions instead of rendering exception templates. 26 | config.action_dispatch.show_exceptions = false 27 | 28 | # Disable request forgery protection in test environment. 29 | config.action_controller.allow_forgery_protection = false 30 | 31 | # Store uploaded files on the local file system in a temporary directory 32 | config.active_storage.service = :test 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Tell Action Mailer not to deliver emails to the real world. 37 | # The :test delivery method accumulates sent emails in the 38 | # ActionMailer::Base.deliveries array. 39 | config.action_mailer.delivery_method = :test 40 | 41 | # Print deprecation notices to the stderr. 42 | config.active_support.deprecation = :stderr 43 | 44 | # Raises error for missing translations 45 | # config.action_view.raise_on_missing_translations = true 46 | end 47 | -------------------------------------------------------------------------------- /config/initializers/acts_as_taggable_on.rb: -------------------------------------------------------------------------------- 1 | ActsAsTaggableOn.remove_unused_tags = true 2 | ActsAsTaggableOn.force_lowercase = true 3 | ActsAsTaggableOn.force_parameterize = true 4 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Avoid CORS issues when API is called from the frontend app. 4 | # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. 5 | 6 | # Read more: https://github.com/cyu/rack-cors 7 | 8 | Rails.application.config.middleware.insert_before 0, Rack::Cors do 9 | allow do 10 | origins '*' 11 | 12 | resource '*', 13 | headers: :any, 14 | methods: [:get, :post, :put, :patch, :delete, :options, :head] 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /config/initializers/friendly_id.rb: -------------------------------------------------------------------------------- 1 | # FriendlyId Global Configuration 2 | # 3 | # Use this to set up shared configuration options for your entire application. 4 | # Any of the configuration options shown here can also be applied to single 5 | # models by passing arguments to the `friendly_id` class method or defining 6 | # methods in your model. 7 | # 8 | # To learn more, check out the guide: 9 | # 10 | # http://norman.github.io/friendly_id/file.Guide.html 11 | 12 | FriendlyId.defaults do |config| 13 | # ## Reserved Words 14 | # 15 | # Some words could conflict with Rails's routes when used as slugs, or are 16 | # undesirable to allow as slugs. Edit this list as needed for your app. 17 | config.use :reserved 18 | 19 | config.reserved_words = %w(new edit index session login logout users admin 20 | stylesheets assets javascripts images) 21 | 22 | # This adds an option to to treat reserved words as conflicts rather than exceptions. 23 | # When there is no good candidate, a UUID will be appended, matching the existing 24 | # conflict behavior. 25 | 26 | # config.treat_reserved_as_conflict = true 27 | 28 | # ## Friendly Finders 29 | # 30 | # Uncomment this to use friendly finders in all models. By default, if 31 | # you wish to find a record by its friendly id, you must do: 32 | # 33 | # MyModel.friendly.find('foo') 34 | # 35 | # If you uncomment this, you can do: 36 | # 37 | # MyModel.find('foo') 38 | # 39 | # This is significantly more convenient but may not be appropriate for 40 | # all applications, so you must explicity opt-in to this behavior. You can 41 | # always also configure it on a per-model basis if you prefer. 42 | # 43 | # Something else to consider is that using the :finders addon boosts 44 | # performance because it will avoid Rails-internal code that makes runtime 45 | # calls to `Module.extend`. 46 | # 47 | # config.use :finders 48 | # 49 | # ## Slugs 50 | # 51 | # Most applications will use the :slugged module everywhere. If you wish 52 | # to do so, uncomment the following line. 53 | # 54 | # config.use :slugged 55 | # 56 | # By default, FriendlyId's :slugged addon expects the slug column to be named 57 | # 'slug', but you can change it if you wish. 58 | # 59 | # config.slug_column = 'slug' 60 | # 61 | # By default, slug has no size limit, but you can change it if you wish. 62 | # 63 | # config.slug_limit = 255 64 | # 65 | # When FriendlyId can not generate a unique ID from your base method, it appends 66 | # a UUID, separated by a single dash. You can configure the character used as the 67 | # separator. If you're upgrading from FriendlyId 4, you may wish to replace this 68 | # with two dashes. 69 | # 70 | # config.sequence_separator = '-' 71 | # 72 | # Note that you must use the :slugged addon **prior** to the line which 73 | # configures the sequence separator, or else FriendlyId will raise an undefined 74 | # method error. 75 | # 76 | # ## Tips and Tricks 77 | # 78 | # ### Controlling when slugs are generated 79 | # 80 | # As of FriendlyId 5.0, new slugs are generated only when the slug field is 81 | # nil, but if you're using a column as your base method can change this 82 | # behavior by overriding the `should_generate_new_friendly_id?` method that 83 | # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave 84 | # more like 4.0. 85 | # Note: Use(include) Slugged module in the config if using the anonymous module. 86 | # If you have `friendly_id :name, use: slugged` in the model, Slugged module 87 | # is included after the anonymous module defined in the initializer, so it 88 | # overrides the `should_generate_new_friendly_id?` method from the anonymous module. 89 | # 90 | # config.use :slugged 91 | # config.use Module.new { 92 | # def should_generate_new_friendly_id? 93 | # slug.blank? || _changed? 94 | # end 95 | # } 96 | # 97 | # FriendlyId uses Rails's `parameterize` method to generate slugs, but for 98 | # languages that don't use the Roman alphabet, that's not usually sufficient. 99 | # Here we use the Babosa library to transliterate Russian Cyrillic slugs to 100 | # ASCII. If you use this, don't forget to add "babosa" to your Gemfile. 101 | # 102 | # config.use Module.new { 103 | # def normalize_friendly_id(text) 104 | # text.to_slug.normalize! :transliterations => [:russian, :latin] 105 | # end 106 | # } 107 | end 108 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/knock.rb: -------------------------------------------------------------------------------- 1 | Knock.setup do |config| 2 | 3 | ## Expiration claim 4 | ## ---------------- 5 | ## 6 | ## How long before a token is expired. If nil is provided, token will 7 | ## last forever. 8 | ## 9 | ## Default: 10 | # config.token_lifetime = 1.day 11 | 12 | 13 | ## Audience claim 14 | ## -------------- 15 | ## 16 | ## Configure the audience claim to identify the recipients that the token 17 | ## is intended for. 18 | ## 19 | ## Default: 20 | # config.token_audience = nil 21 | 22 | ## If using Auth0, uncomment the line below 23 | # config.token_audience = -> { Rails.application.secrets.auth0_client_id } 24 | 25 | ## Signature algorithm 26 | ## ------------------- 27 | ## 28 | ## Configure the algorithm used to encode the token 29 | ## 30 | ## Default: 31 | # config.token_signature_algorithm = 'HS256' 32 | 33 | ## Signature key 34 | ## ------------- 35 | ## 36 | ## Configure the key used to sign tokens. 37 | ## 38 | ## Default: 39 | # config.token_secret_signature_key = -> { Rails.application.secrets.secret_key_base } 40 | 41 | ## If using Auth0, uncomment the line below 42 | # config.token_secret_signature_key = -> { JWT.base64url_decode Rails.application.secrets.auth0_client_secret } 43 | 44 | ## Public key 45 | ## ---------- 46 | ## 47 | ## Configure the public key used to decode tokens, if required. 48 | ## 49 | ## Default: 50 | # config.token_public_key = nil 51 | 52 | ## Exception Class 53 | ## --------------- 54 | ## 55 | ## Configure the exception to be used when user cannot be found. 56 | ## 57 | ## Default: 58 | # config.not_found_exception_class_name = 'ActiveRecord::RecordNotFound' 59 | end 60 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at http://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | threads threads_count, threads_count 9 | 10 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 11 | # 12 | port ENV.fetch("PORT") { 3000 } 13 | 14 | # Specifies the `environment` that Puma will run in. 15 | # 16 | environment ENV.fetch("RAILS_ENV") { "development" } 17 | 18 | # Specifies the number of `workers` to boot in clustered mode. 19 | # Workers are forked webserver processes. If using threads and workers together 20 | # the concurrency of the application would be max `threads` * `workers`. 21 | # Workers do not work on JRuby or Windows (both of which do not support 22 | # processes). 23 | # 24 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 25 | 26 | # Use the `preload_app!` method when specifying a `workers` number. 27 | # This directive tells Puma to first boot the application and load code 28 | # before forking the application. This takes advantage of Copy On Write 29 | # process behavior so workers use less memory. 30 | # 31 | # preload_app! 32 | 33 | # Allow puma to be restarted by `rails restart` command. 34 | plugin :tmp_restart 35 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 3 | post '/graphql', to: 'graphql#execute' 4 | 5 | mount GraphiQL::Rails::Engine, at: '/graphiql', graphql_path: '/graphql' 6 | end 7 | -------------------------------------------------------------------------------- /config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rails secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | # Shared secrets are available across all environments. 14 | 15 | # shared: 16 | # api_key: a1B2c3D4e5F6 17 | 18 | # Environmental secrets are only available for that specific environment. 19 | 20 | development: 21 | secret_key_base: 6a3036f5a270b8e2bc5df36aa2ebfca527f3c390836be13fbf5b2fb890610cf35293b7c6b65e62f4b51a8055a46c2643f98c44a13524c6bb5261d483708c0041 22 | 23 | test: 24 | secret_key_base: 956d4323d775461ef8018e4a8d942e77255432532b440afa7eaeda0b57c31a09fab7b9fba153be9886c07352208945af248cbe47febb965fd79fdbf3fd428355 25 | 26 | # Do not keep production secrets in the unencrypted secrets file. 27 | # Instead, either read values from the environment. 28 | # Or, use `bin/rails secrets:setup` to configure encrypted secrets 29 | # and move the `production:` environment over there. 30 | 31 | production: 32 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 33 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | %w[ 2 | .ruby-version 3 | .rbenv-vars 4 | tmp/restart.txt 5 | tmp/caching-dev.txt 6 | ].each { |path| Spring.watch(path) } 7 | -------------------------------------------------------------------------------- /config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: <%= Rails.root.join("tmp/storage") %> 4 | 5 | local: 6 | service: Disk 7 | root: <%= Rails.root.join("storage") %> 8 | 9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) 10 | # amazon: 11 | # service: S3 12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> 13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> 14 | # region: us-east-1 15 | # bucket: your_own_bucket 16 | 17 | # Remember not to checkin your GCS keyfile to a repository 18 | # google: 19 | # service: GCS 20 | # project: your_project 21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> 22 | # bucket: your_own_bucket 23 | 24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) 25 | # microsoft: 26 | # service: AzureStorage 27 | # storage_account_name: your_account_name 28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> 29 | # container: your_container_name 30 | 31 | # mirror: 32 | # service: Mirror 33 | # primary: local 34 | # mirrors: [ amazon, google, microsoft ] 35 | -------------------------------------------------------------------------------- /db/migrate/20180622093617_create_users.rb: -------------------------------------------------------------------------------- 1 | class CreateUsers < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :users do |t| 4 | t.string :username 5 | t.string :email 6 | t.string :password_digest 7 | t.string :bio 8 | t.string :image 9 | t.integer :follows_count, default: 0 10 | 11 | t.timestamps 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20180622112835_create_articles.rb: -------------------------------------------------------------------------------- 1 | class CreateArticles < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :articles do |t| 4 | t.string :title 5 | t.string :slug 6 | t.string :description 7 | t.string :body 8 | t.integer :favorites_count, default: 0 9 | t.belongs_to :author, references: :users, index: true 10 | 11 | t.timestamps 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /db/migrate/20180622160324_create_friendly_id_slugs.rb: -------------------------------------------------------------------------------- 1 | migration_class = 2 | if ActiveRecord::VERSION::MAJOR >= 5 3 | ActiveRecord::Migration[4.2] 4 | else 5 | ActiveRecord::Migration 6 | end 7 | 8 | class CreateFriendlyIdSlugs < migration_class 9 | def change 10 | create_table :friendly_id_slugs do |t| 11 | t.string :slug, :null => false 12 | t.integer :sluggable_id, :null => false 13 | t.string :sluggable_type, :limit => 50 14 | t.string :scope 15 | t.datetime :created_at 16 | end 17 | add_index :friendly_id_slugs, :sluggable_id 18 | add_index :friendly_id_slugs, [:slug, :sluggable_type], length: { slug: 140, sluggable_type: 50 } 19 | add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], length: { slug: 70, sluggable_type: 50, scope: 70 }, unique: true 20 | add_index :friendly_id_slugs, :sluggable_type 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /db/migrate/20180622173640_create_comments.rb: -------------------------------------------------------------------------------- 1 | class CreateComments < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :comments do |t| 4 | t.string :body 5 | t.belongs_to :author, references: :users, index: true 6 | t.belongs_to :article, index: true 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /db/migrate/20180622221043_create_favorites.rb: -------------------------------------------------------------------------------- 1 | class CreateFavorites < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :favorites do |t| 4 | t.belongs_to :user, index: true 5 | t.belongs_to :article, index: true 6 | 7 | t.timestamps 8 | 9 | t.index [:user_id, :article_id], unique: true 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20180625175104_create_follows.rb: -------------------------------------------------------------------------------- 1 | class CreateFollows < ActiveRecord::Migration[5.1] 2 | def change 3 | create_table :follows do |t| 4 | t.belongs_to :follower, index: true 5 | t.belongs_to :followee, index: true 6 | 7 | t.timestamps 8 | 9 | t.index [:follower_id, :followee_id], unique: true 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20180625195100_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 1) 2 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 3 | class ActsAsTaggableOnMigration < ActiveRecord::Migration[4.2]; end 4 | else 5 | class ActsAsTaggableOnMigration < ActiveRecord::Migration; end 6 | end 7 | ActsAsTaggableOnMigration.class_eval do 8 | def self.up 9 | create_table :tags do |t| 10 | t.string :name 11 | end 12 | 13 | create_table :taggings do |t| 14 | t.references :tag 15 | 16 | # You should make sure that the column created is 17 | # long enough to store the required class names. 18 | t.references :taggable, polymorphic: true 19 | t.references :tagger, polymorphic: true 20 | 21 | # Limit is created to prevent MySQL error on index 22 | # length for MyISAM table type: http://bit.ly/vgW2Ql 23 | t.string :context, limit: 128 24 | 25 | t.datetime :created_at 26 | end 27 | 28 | add_index :taggings, :tag_id 29 | add_index :taggings, [:taggable_id, :taggable_type, :context] 30 | end 31 | 32 | def self.down 33 | drop_table :taggings 34 | drop_table :tags 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /db/migrate/20180625195101_add_missing_unique_indices.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 2) 2 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 3 | class AddMissingUniqueIndices < ActiveRecord::Migration[4.2]; end 4 | else 5 | class AddMissingUniqueIndices < ActiveRecord::Migration; end 6 | end 7 | AddMissingUniqueIndices.class_eval do 8 | def self.up 9 | add_index :tags, :name, unique: true 10 | 11 | remove_index :taggings, :tag_id if index_exists?(:taggings, :tag_id) 12 | remove_index :taggings, [:taggable_id, :taggable_type, :context] 13 | add_index :taggings, 14 | [:tag_id, :taggable_id, :taggable_type, :context, :tagger_id, :tagger_type], 15 | unique: true, name: 'taggings_idx' 16 | end 17 | 18 | def self.down 19 | remove_index :tags, :name 20 | 21 | remove_index :taggings, name: 'taggings_idx' 22 | 23 | add_index :taggings, :tag_id unless index_exists?(:taggings, :tag_id) 24 | add_index :taggings, [:taggable_id, :taggable_type, :context] 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /db/migrate/20180625195102_add_taggings_counter_cache_to_tags.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 3) 2 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 3 | class AddTaggingsCounterCacheToTags < ActiveRecord::Migration[4.2]; end 4 | else 5 | class AddTaggingsCounterCacheToTags < ActiveRecord::Migration; end 6 | end 7 | AddTaggingsCounterCacheToTags.class_eval do 8 | def self.up 9 | add_column :tags, :taggings_count, :integer, default: 0 10 | 11 | ActsAsTaggableOn::Tag.reset_column_information 12 | ActsAsTaggableOn::Tag.find_each do |tag| 13 | ActsAsTaggableOn::Tag.reset_counters(tag.id, :taggings) 14 | end 15 | end 16 | 17 | def self.down 18 | remove_column :tags, :taggings_count 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /db/migrate/20180625195103_add_missing_taggable_index.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 4) 2 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 3 | class AddMissingTaggableIndex < ActiveRecord::Migration[4.2]; end 4 | else 5 | class AddMissingTaggableIndex < ActiveRecord::Migration; end 6 | end 7 | AddMissingTaggableIndex.class_eval do 8 | def self.up 9 | add_index :taggings, [:taggable_id, :taggable_type, :context] 10 | end 11 | 12 | def self.down 13 | remove_index :taggings, [:taggable_id, :taggable_type, :context] 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /db/migrate/20180625195104_change_collation_for_tag_names.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 5) 2 | # This migration is added to circumvent issue #623 and have special characters 3 | # work properly 4 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 5 | class ChangeCollationForTagNames < ActiveRecord::Migration[4.2]; end 6 | else 7 | class ChangeCollationForTagNames < ActiveRecord::Migration; end 8 | end 9 | ChangeCollationForTagNames.class_eval do 10 | def up 11 | if ActsAsTaggableOn::Utils.using_mysql? 12 | execute("ALTER TABLE tags MODIFY name varchar(255) CHARACTER SET utf8 COLLATE utf8_bin;") 13 | end 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /db/migrate/20180625195105_add_missing_indexes_on_taggings.acts_as_taggable_on_engine.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from acts_as_taggable_on_engine (originally 6) 2 | if ActiveRecord.gem_version >= Gem::Version.new('5.0') 3 | class AddMissingIndexesOnTaggings < ActiveRecord::Migration[4.2]; end 4 | else 5 | class AddMissingIndexesOnTaggings < ActiveRecord::Migration; end 6 | end 7 | AddMissingIndexesOnTaggings.class_eval do 8 | def change 9 | add_index :taggings, :tag_id unless index_exists? :taggings, :tag_id 10 | add_index :taggings, :taggable_id unless index_exists? :taggings, :taggable_id 11 | add_index :taggings, :taggable_type unless index_exists? :taggings, :taggable_type 12 | add_index :taggings, :tagger_id unless index_exists? :taggings, :tagger_id 13 | add_index :taggings, :context unless index_exists? :taggings, :context 14 | 15 | unless index_exists? :taggings, [:tagger_id, :tagger_type] 16 | add_index :taggings, [:tagger_id, :tagger_type] 17 | end 18 | 19 | unless index_exists? :taggings, [:taggable_id, :taggable_type, :tagger_id, :context], name: 'taggings_idy' 20 | add_index :taggings, [:taggable_id, :taggable_type, :tagger_id, :context], name: 'taggings_idy' 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2018_06_25_195105) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "articles", force: :cascade do |t| 19 | t.string "title" 20 | t.string "slug" 21 | t.string "description" 22 | t.string "body" 23 | t.integer "favorites_count", default: 0 24 | t.integer "author_id" 25 | t.datetime "created_at", null: false 26 | t.datetime "updated_at", null: false 27 | t.index ["author_id"], name: "index_articles_on_author_id" 28 | end 29 | 30 | create_table "comments", force: :cascade do |t| 31 | t.string "body" 32 | t.integer "author_id" 33 | t.integer "article_id" 34 | t.datetime "created_at", null: false 35 | t.datetime "updated_at", null: false 36 | t.index ["article_id"], name: "index_comments_on_article_id" 37 | t.index ["author_id"], name: "index_comments_on_author_id" 38 | end 39 | 40 | create_table "favorites", force: :cascade do |t| 41 | t.integer "user_id" 42 | t.integer "article_id" 43 | t.datetime "created_at", null: false 44 | t.datetime "updated_at", null: false 45 | t.index ["article_id"], name: "index_favorites_on_article_id" 46 | t.index ["user_id", "article_id"], name: "index_favorites_on_user_id_and_article_id", unique: true 47 | t.index ["user_id"], name: "index_favorites_on_user_id" 48 | end 49 | 50 | create_table "follows", force: :cascade do |t| 51 | t.integer "follower_id" 52 | t.integer "followee_id" 53 | t.datetime "created_at", null: false 54 | t.datetime "updated_at", null: false 55 | t.index ["followee_id"], name: "index_follows_on_followee_id" 56 | t.index ["follower_id", "followee_id"], name: "index_follows_on_follower_id_and_followee_id", unique: true 57 | t.index ["follower_id"], name: "index_follows_on_follower_id" 58 | end 59 | 60 | create_table "friendly_id_slugs", force: :cascade do |t| 61 | t.string "slug", null: false 62 | t.integer "sluggable_id", null: false 63 | t.string "sluggable_type", limit: 50 64 | t.string "scope" 65 | t.datetime "created_at" 66 | t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true 67 | t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type" 68 | t.index ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id" 69 | t.index ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type" 70 | end 71 | 72 | create_table "taggings", force: :cascade do |t| 73 | t.integer "tag_id" 74 | t.string "taggable_type" 75 | t.integer "taggable_id" 76 | t.string "tagger_type" 77 | t.integer "tagger_id" 78 | t.string "context", limit: 128 79 | t.datetime "created_at" 80 | t.index ["context"], name: "index_taggings_on_context" 81 | t.index ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true 82 | t.index ["tag_id"], name: "index_taggings_on_tag_id" 83 | t.index ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context" 84 | t.index ["taggable_id", "taggable_type", "tagger_id", "context"], name: "taggings_idy" 85 | t.index ["taggable_id"], name: "index_taggings_on_taggable_id" 86 | t.index ["taggable_type"], name: "index_taggings_on_taggable_type" 87 | t.index ["tagger_id", "tagger_type"], name: "index_taggings_on_tagger_id_and_tagger_type" 88 | t.index ["tagger_id"], name: "index_taggings_on_tagger_id" 89 | end 90 | 91 | create_table "tags", force: :cascade do |t| 92 | t.string "name" 93 | t.integer "taggings_count", default: 0 94 | t.index ["name"], name: "index_tags_on_name", unique: true 95 | end 96 | 97 | create_table "users", force: :cascade do |t| 98 | t.string "username" 99 | t.string "email" 100 | t.string "password_digest" 101 | t.string "bio" 102 | t.string "image" 103 | t.integer "follows_count", default: 0 104 | t.datetime "created_at", null: false 105 | t.datetime "updated_at", null: false 106 | end 107 | 108 | end 109 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | 9 | eric = User.create!( 10 | username: 'Eric Simons', 11 | email: 'eric@example.com', 12 | bio: "Cofounder @GoThinkster, lived in Aol's HQ for a few months, kinda looks like Peeta from the Hunger Games", 13 | password: 'secret', 14 | image: 'http://i.imgur.com/Qr71crq.jpg' 15 | ) 16 | 17 | albert = User.create!( 18 | username: 'Albert Pai', 19 | email: 'albert@example.com', 20 | password: 'secret', 21 | image: 'http://i.imgur.com/N4VcUeJ.jpg' 22 | ) 23 | 24 | dostu = User.create!( 25 | username: 'dostu', 26 | email: 'donatas.stundys@gmail.com', 27 | bio: 'GraphQL enthusiast', 28 | password: 'secret', 29 | image: 'https://image.ibb.co/gH6AUo/dostu.jpg' 30 | ) 31 | 32 | eric.followees << dostu 33 | eric.followees << albert 34 | 35 | 10.times { |i| 36 | Article.create!( 37 | title: "Eric article ##{i}", 38 | description: 'This is the description for the post.', 39 | body: "Web development technologies have evolved at an incredible clip over the past few years.\n\n## Introducing RealWorld.\n\nIt's a great solution for learning how other frameworks work.", 40 | tag_list: 'graphql', 41 | author: eric 42 | ) 43 | } 44 | 45 | 10.times { |i| 46 | Article.create!( 47 | title: "Albert article ##{i}", 48 | description: 'This is the description for the post.', 49 | body: "Web development technologies have evolved at an incredible clip over the past few years.\n\n## Introducing RealWorld.\n\nIt's a great solution for learning how other frameworks work.", 50 | tag_list: 'graphql', 51 | author: albert 52 | ) 53 | } 54 | 55 | article = Article.create!( 56 | title: 'How to build webapps that scale', 57 | description: 'This is the description for the post.', 58 | body: "Web development technologies have evolved at an incredible clip over the past few years.\n\n## Introducing RealWorld.\n\nIt's a great solution for learning how other frameworks work.", 59 | tag_list: ['rails', 'graphql'], 60 | author: dostu 61 | ) 62 | 63 | eric.favorite_articles << article 64 | albert.favorite_articles << article 65 | -------------------------------------------------------------------------------- /graphql-schema.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/graphql-schema.png -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/lib/tasks/.keep -------------------------------------------------------------------------------- /lib/tasks/graphql.rake: -------------------------------------------------------------------------------- 1 | namespace :graphql do 2 | task schema: :environment do 3 | schema_defn = RealworldSchema.to_definition 4 | schema_path = 'app/graphql/schema.graphql' 5 | File.write(Rails.root.join(schema_path), schema_defn) 6 | puts "Updated #{schema_path}" 7 | end 8 | 9 | task docs: :environment do 10 | GraphQLDocs.build( 11 | filename: 'app/graphql/schema.graphql', 12 | output_dir: 'public/docs', 13 | base_url: '/docs' 14 | ) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/log/.keep -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/logo.png -------------------------------------------------------------------------------- /public/docs/assets/images/graphiql-headers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/images/graphiql-headers.png -------------------------------------------------------------------------------- /public/docs/assets/images/graphiql-variables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/images/graphiql-variables.png -------------------------------------------------------------------------------- /public/docs/assets/images/graphiql.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/images/graphiql.png -------------------------------------------------------------------------------- /public/docs/assets/images/menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/images/menu.png -------------------------------------------------------------------------------- /public/docs/assets/images/navbar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/images/navbar.png -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_B_0.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_B_0.eot -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_B_0.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_B_0.ttf -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_B_0.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_B_0.woff -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_B_0.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_B_0.woff2 -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_C_0.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_C_0.eot -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_C_0.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_C_0.ttf -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_C_0.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_C_0.woff -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_C_0.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_C_0.woff2 -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_D_0.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_D_0.eot -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_D_0.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_D_0.ttf -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_D_0.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_D_0.woff -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_D_0.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_D_0.woff2 -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_E_0.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_E_0.eot -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_E_0.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_E_0.ttf -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_E_0.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_E_0.woff -------------------------------------------------------------------------------- /public/docs/assets/webfonts/2C4B9D_E_0.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/public/docs/assets/webfonts/2C4B9D_E_0.woff2 -------------------------------------------------------------------------------- /public/docs/scalar/boolean/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Boolean 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | Boolean

529 |

Represents true or false values.

530 | 531 |
532 | 533 | 534 |
535 | 536 | 539 |
540 |
541 | 542 |
543 | 544 | 545 | 546 | -------------------------------------------------------------------------------- /public/docs/scalar/datetime/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | DateTime 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | DateTime

529 | 530 |
531 | 532 | 533 |
534 | 535 | 538 |
539 |
540 | 541 |
542 | 543 | 544 | 545 | -------------------------------------------------------------------------------- /public/docs/scalar/float/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Float 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | Float

529 |

Represents signed double-precision fractional values as specified by IEEE 754.

530 | 531 |
532 | 533 | 534 |
535 | 536 | 539 |
540 |
541 | 542 |
543 | 544 | 545 | 546 | -------------------------------------------------------------------------------- /public/docs/scalar/int/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Int 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | Int

529 |

Represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.

530 | 531 |
532 | 533 | 534 |
535 | 536 | 539 |
540 |
541 | 542 |
543 | 544 | 545 | 546 | -------------------------------------------------------------------------------- /public/docs/scalar/iso8601datetime/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ISO8601DateTime 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | ISO8601DateTime

529 |

An ISO 8601-encoded datetime

530 | 531 |
532 | 533 | 534 |
535 | 536 | 539 |
540 |
541 | 542 |
543 | 544 | 545 | 546 | -------------------------------------------------------------------------------- /public/docs/scalar/string/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | String 8 | 9 | 10 | 23 | 24 | 25 | 26 |
27 | 29 | 525 |
526 | 527 |

528 | String

529 |

Represents textual data as UTF-8 character sequences. This type is most often used by GraphQL to represent free-form human-readable text.

530 | 531 |
532 | 533 | 534 |
535 | 536 | 539 |
540 |
541 | 542 |
543 | 544 | 545 | 546 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /spec/factories/articles.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :article do 3 | title { 'Title' } 4 | description { 'Description' } 5 | body { 'Body' } 6 | tag_list { %w[tag1 tag2] } 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/factories/users.rb: -------------------------------------------------------------------------------- 1 | FactoryBot.define do 2 | factory :user do 3 | username { 'User' } 4 | email { 'user@example.com' } 5 | password { 'secret' } 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/graphql/mutations/add_comment_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe Mutations::AddComment do 4 | let!(:user) { create :user } 5 | let!(:article) { create :article, author: user } 6 | 7 | def perform(article_id:, body:) 8 | described_class.new(object: nil, field: nil, context: { current_user: user }).resolve( 9 | article_id: article_id, body: body 10 | ) 11 | end 12 | 13 | it 'adds a comment to an article' do 14 | result = perform( 15 | article_id: article.id, 16 | body: 'Comment' 17 | ) 18 | 19 | expect(result[:errors]).to be_empty 20 | expect(result[:comment]).to have_attributes(body: 'Comment') 21 | end 22 | 23 | it 'returns errors' do 24 | result = perform( 25 | article_id: article.id, 26 | body: ' ' 27 | ) 28 | 29 | expect(result[:errors]).to eq([UserError.new("Body can't be blank")]) 30 | expect(result[:comment]).to be_nil 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/graphql/mutations/create_article_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe Mutations::CreateArticle do 4 | let!(:user) { create :user } 5 | 6 | def perform(title:, description:, body:, tag_list:) 7 | described_class.new(object: nil, field: nil, context: { current_user: user }).resolve( 8 | title: title, description: description, body: body, tag_list: tag_list 9 | ) 10 | end 11 | 12 | it 'creates a new article' do 13 | result = perform( 14 | title: 'Title', 15 | description: 'Description', 16 | body: 'Body', 17 | tag_list: %w[tag1 tag2] 18 | ) 19 | 20 | expect(result[:errors]).to be_empty 21 | expect(result[:article]).to have_attributes( 22 | title: 'Title', 23 | description: 'Description', 24 | body: 'Body', 25 | tag_list: %w[tag1 tag2] 26 | ) 27 | end 28 | 29 | it 'returns errors' do 30 | result = perform( 31 | title: 'Title', 32 | description: 'Description', 33 | body: ' ', 34 | tag_list: %w[tag1 tag2] 35 | ) 36 | 37 | expect(result[:errors]).to eq([UserError.new("Body can't be blank")]) 38 | expect(result[:article]).to be_nil 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/graphql/mutations/create_user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe Mutations::CreateUser do 4 | def perform(username:, email:, password:) 5 | described_class.new(object: nil, field: nil, context: {}).resolve( 6 | username: username, email: email, password: password 7 | ) 8 | end 9 | 10 | it 'creates a new user' do 11 | result = perform( 12 | username: 'Test User', 13 | email: 'email@example.com', 14 | password: '[omitted]' 15 | ) 16 | 17 | user = result[:user] 18 | 19 | expect(user).to be_persisted 20 | expect(user.username).to eq('Test User') 21 | expect(user.email).to eq('email@example.com') 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /spec/graphql/mutations/sign_in_user_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | describe Mutations::SignInUser do 4 | let!(:user) { create :user } 5 | 6 | def perform(email:, password:) 7 | described_class.new(object: nil, field: nil, context: {}).resolve( 8 | email: email, password: password 9 | ) 10 | end 11 | 12 | it 'creates a token' do 13 | result = perform( 14 | email: user.email, 15 | password: user.password 16 | ) 17 | 18 | expect(result).to be_present 19 | expect(result[:token]).to be_present 20 | expect(result[:viewer]).to eq(user) 21 | end 22 | 23 | it 'handles no credentials' do 24 | expect(perform(email: nil, password: nil)).to eq( 25 | errors: [UserError.new('email or password is invalid')] 26 | ) 27 | end 28 | 29 | it 'handles wrong email' do 30 | expect(perform(email: 'wrong', password: nil)).to eq( 31 | errors: [UserError.new('email or password is invalid')] 32 | ) 33 | end 34 | 35 | it 'handles wrong password' do 36 | expect(perform(email: user.email, password: 'wrong')).to eq( 37 | errors: [UserError.new('email or password is invalid')] 38 | ) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/graphql/realword_schema_spec.rb: -------------------------------------------------------------------------------- 1 | require 'rails_helper' 2 | 3 | # Run `bundle exec rails graphql:schema` to update 4 | 5 | describe RealworldSchema do 6 | def execute_graphql_query(query, variables = {}, context = {}) 7 | result = RealworldSchema.execute( 8 | query, 9 | variables: variables, 10 | context: context 11 | ) 12 | 13 | pp result if result['errors'] 14 | 15 | result 16 | end 17 | 18 | it 'contains latest changes' do 19 | current_defn = RealworldSchema.to_definition 20 | printout_defn = File.read(Rails.root.join('app', 'graphql', 'schema.graphql')) 21 | expect(current_defn).to eq(printout_defn), 'Update the printed schema with `bundle exec rake graphql:schema`' 22 | end 23 | 24 | describe 'feed' do 25 | it 'is works' do 26 | create :article, author: create(:user) 27 | result = execute_graphql_query('{ articles { edges { node { title } } } }') 28 | expect(result.dig('data', 'articles', 'edges').first['node']).to eq('title' => 'Title') 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /spec/rails_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | require 'spec_helper' 3 | ENV['RAILS_ENV'] ||= 'test' 4 | require File.expand_path('../config/environment', __dir__) 5 | # Prevent database truncation if the environment is production 6 | abort('The Rails environment is running in production mode!') if Rails.env.production? 7 | require 'rspec/rails' 8 | # Add additional requires below this line. Rails is not loaded until this point! 9 | 10 | # Requires supporting ruby files with custom matchers and macros, etc, in 11 | # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are 12 | # run as spec files by default. This means that files in spec/support that end 13 | # in _spec.rb will both be required and run as specs, causing the specs to be 14 | # run twice. It is recommended that you do not name files matching this glob to 15 | # end with _spec.rb. You can configure this pattern with the --pattern 16 | # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. 17 | # 18 | # The following line is provided for convenience purposes. It has the downside 19 | # of increasing the boot-up time by auto-requiring all files in the support 20 | # directory. Alternatively, in the individual `*_spec.rb` files, manually 21 | # require only the support files necessary. 22 | # 23 | Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } 24 | 25 | # Checks for pending migrations and applies them before tests are run. 26 | # If you are not using ActiveRecord, you can remove this line. 27 | ActiveRecord::Migration.maintain_test_schema! 28 | 29 | RSpec.configure do |config| 30 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 31 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 32 | 33 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 34 | # examples within a transaction, remove the following line or assign false 35 | # instead of true. 36 | config.use_transactional_fixtures = true 37 | 38 | # RSpec Rails can automatically mix in different behaviours to your tests 39 | # based on their file location, for example enabling you to call `get` and 40 | # `post` in specs under `spec/controllers`. 41 | # 42 | # You can disable this behaviour by removing the line below, and instead 43 | # explicitly tag your specs with their type, e.g.: 44 | # 45 | # RSpec.describe UsersController, :type => :controller do 46 | # # ... 47 | # end 48 | # 49 | # The different available types are documented in the features, such as in 50 | # https://relishapp.com/rspec/rspec-rails/docs 51 | config.infer_spec_type_from_file_location! 52 | 53 | # Filter lines from Rails gems in backtraces. 54 | config.filter_rails_from_backtrace! 55 | # arbitrary gems may also be filtered via: 56 | # config.filter_gems_from_backtrace("gem name") 57 | end 58 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file was generated by the `rails generate rspec:install` command. Conventionally, all 2 | # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. 3 | # The generated `.rspec` file contains `--require spec_helper` which will cause 4 | # this file to always be loaded, without a need to explicitly require it in any 5 | # files. 6 | # 7 | # Given that it is always loaded, you are encouraged to keep this file as 8 | # light-weight as possible. Requiring heavyweight dependencies from this file 9 | # will add to the boot time of your test suite on EVERY test run, even for an 10 | # individual file that may not need all of that loaded. Instead, consider making 11 | # a separate helper file that requires the additional dependencies and performs 12 | # the additional setup, and require it from the spec files that actually need 13 | # it. 14 | # 15 | # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration 16 | RSpec.configure do |config| 17 | # rspec-expectations config goes here. You can use an alternate 18 | # assertion/expectation library such as wrong or the stdlib/minitest 19 | # assertions if you prefer. 20 | config.expect_with :rspec do |expectations| 21 | # This option will default to `true` in RSpec 4. It makes the `description` 22 | # and `failure_message` of custom matchers include text for helper methods 23 | # defined using `chain`, e.g.: 24 | # be_bigger_than(2).and_smaller_than(4).description 25 | # # => "be bigger than 2 and smaller than 4" 26 | # ...rather than: 27 | # # => "be bigger than 2" 28 | expectations.include_chain_clauses_in_custom_matcher_descriptions = true 29 | end 30 | 31 | # rspec-mocks config goes here. You can use an alternate test double 32 | # library (such as bogus or mocha) by changing the `mock_with` option here. 33 | config.mock_with :rspec do |mocks| 34 | # Prevents you from mocking or stubbing a method that does not exist on 35 | # a real object. This is generally recommended, and will default to 36 | # `true` in RSpec 4. 37 | mocks.verify_partial_doubles = true 38 | end 39 | 40 | # This option will default to `:apply_to_host_groups` in RSpec 4 (and will 41 | # have no way to turn it off -- the option exists only for backwards 42 | # compatibility in RSpec 3). It causes shared context metadata to be 43 | # inherited by the metadata hash of host groups and examples, rather than 44 | # triggering implicit auto-inclusion in groups with matching metadata. 45 | config.shared_context_metadata_behavior = :apply_to_host_groups 46 | end 47 | -------------------------------------------------------------------------------- /spec/support/factory_bot.rb: -------------------------------------------------------------------------------- 1 | RSpec.configure do |config| 2 | config.include FactoryBot::Syntax::Methods 3 | end 4 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/tmp/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dostu/rails-graphql-realworld-example-app/08526482a85aeceb3ac2531430e0ce0d246fe362/vendor/.keep --------------------------------------------------------------------------------