Skip to content

Instantly share code, notes, and snippets.

@ksoda
Forked from clupprich/rails_single_file.rb
Last active November 3, 2021 14:25
Show Gist options
  • Save ksoda/75271e57b793926583b51146e586cf76 to your computer and use it in GitHub Desktop.
Save ksoda/75271e57b793926583b51146e586cf76 to your computer and use it in GitHub Desktop.
begin
require 'bundler/inline'
rescue LoadError => e
warn 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails'
gem 'sqlite3'
gem 'puma'
end
require 'active_record'
require 'action_controller/railtie'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'test.db' # not :memory:
)
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :books, force: true do |t|
t.string :name
end
create_table :categories, force: true do |t|
t.string :name
end
create_table :categorizations, force: true do |t|
t.references :book
t.references :category
t.boolean :primary, default: false, null: false
end
end
class Book < ActiveRecord::Base
has_many :categorizations
has_many :categories, through: :categorizations
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :books, through: :categorizations
def self.primaries
Category.joins(:categorizations).merge(Categorization.primaries)
end
end
class Categorization < ActiveRecord::Base
belongs_to :book
belongs_to :category
def self.primaries
where(primary: true)
end
end
class TestApp < Rails::Application
secrets.secret_token = 'secret_token'
secrets.secret_key_base = 'secret_key_base'
config.logger = Logger.new($stdout)
Rails.logger = config.logger
routes.append do # not routes.draw
resources :primary_categories, only: :index
end
config.consider_all_requests_local = true
end
class PrimaryCategoriesController < ActionController::Base
include Rails.application.routes.url_helpers
def index
@primary_categories = Category.primaries
render inline: '# of primary categories: <%= @primary_categories.count %>'
end
end
if __FILE__ == $0
TestApp.initialize!
Rack::Server.new(app: TestApp, Port: 3000).start
else
require 'minitest/autorun'
class PrimaryCategoriesTest < ActionDispatch::IntegrationTest # :nodoc:
test 'not works' do
get '/primary_categories'
assert_equal 403, status
end
private
def app
Rails.application
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment