fake_app.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. require 'active_record'
  2. require 'action_controller/railtie'
  3. require 'action_view/railtie'
  4. # database
  5. ActiveRecord::Base.configurations = {'test' => {:adapter => 'sqlite3', :database => ':memory:'}}
  6. ActiveRecord::Base.establish_connection('test')
  7. # config
  8. app = Class.new(Rails::Application)
  9. app.config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
  10. app.config.session_store :cookie_store, :key => "_myapp_session"
  11. app.config.active_support.deprecation = :log
  12. app.initialize!
  13. # routes
  14. app.routes.draw do
  15. resources :users
  16. end
  17. # models
  18. class User < ActiveRecord::Base
  19. has_many :authorships
  20. has_many :readerships
  21. has_many :books_authored, :through => :authorships, :source => :book
  22. has_many :books_read, :through => :readerships, :source => :book
  23. def readers
  24. User.joins(:books_read => :authors).where(:authors_books => {:id => self})
  25. end
  26. scope :by_name, order(:name)
  27. scope :by_read_count, lambda {
  28. cols = if connection.adapter_name == "PostgreSQL"
  29. column_names.map { |column| %{"users"."#{column}"} }.join(", ")
  30. else
  31. '"users"."id"'
  32. end
  33. group(cols).select("count(readerships.id) AS read_count, #{cols}").order('read_count DESC')
  34. }
  35. end
  36. class Authorship < ActiveRecord::Base
  37. belongs_to :user
  38. belongs_to :book
  39. end
  40. class Readership < ActiveRecord::Base
  41. belongs_to :user
  42. belongs_to :book
  43. end
  44. class Book < ActiveRecord::Base
  45. has_many :authorships
  46. has_many :readerships
  47. has_many :authors, :through => :authorships, :source => :user
  48. has_many :readers, :through => :readerships, :source => :user
  49. end
  50. # a model that is a descendant of AR::Base but doesn't directly inherit AR::Base
  51. class Admin < User
  52. end
  53. # controllers
  54. class ApplicationController < ActionController::Base; end
  55. class UsersController < ApplicationController
  56. def index
  57. @users = User.page params[:page]
  58. render :inline => <<-ERB
  59. <%= @users.map(&:name).join("\n") %>
  60. <%= paginate @users %>
  61. ERB
  62. end
  63. end
  64. # helpers
  65. Object.const_set(:ApplicationHelper, Module.new)
  66. #migrations
  67. class CreateAllTables < ActiveRecord::Migration
  68. def self.up
  69. create_table(:gem_defined_models) { |t| t.string :name; t.integer :age }
  70. create_table(:users) {|t| t.string :name; t.integer :age}
  71. create_table(:books) {|t| t.string :title}
  72. create_table(:readerships) {|t| t.integer :user_id; t.integer :book_id }
  73. create_table(:authorships) {|t| t.integer :user_id; t.integer :book_id }
  74. end
  75. end