Skip to content

Commit 681f948

Browse files
[Active Record] Add belongs_to_resource to active record
1 parent add2652 commit 681f948

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed

Gemfile

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ branch = ENV.fetch("BRANCH", "main")
88
gem "activesupport", github: "rails/rails", branch: branch
99
gem "activemodel", github: "rails/rails", branch: branch
1010
gem "activejob", github: "rails/rails", branch: branch
11+
gem "activerecord", github: "rails/rails", branch: branch
12+
gem "sqlite3"
1113

1214
gem "rubocop"
1315
gem "rubocop-minitest"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# frozen_string_literal: true
2+
3+
module ActiveResource
4+
module Associations
5+
module ActiveRecord
6+
def belongs_to_resource(name, class_name: nil)
7+
klass = class_name&.constantize || name.to_s.classify.constantize
8+
define_method(name) { klass.find(send("#{name}_id")) }
9+
end
10+
end
11+
end
12+
end

lib/active_resource/railtie.rb

+6
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,11 @@ class Railtie < Rails::Railtie
2121
app.config.active_job.custom_serializers << ActiveResource::ActiveJobSerializer
2222
end
2323
end
24+
25+
initializer "active_resource.patch_active_record" do |app|
26+
ActiveSupport.on_load(:active_record) do
27+
ActiveRecord::Base.extend(ActiveResource::Associations::ActiveRecord)
28+
end
29+
end
2430
end
2531
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# frozen_string_literal: true
2+
3+
require "active_record"
4+
require "active_resource/associations/active_record"
5+
6+
class ActiveRecordAssociationTest < ActiveSupport::TestCase
7+
setup do
8+
setup_response # find me in abstract_unit
9+
10+
ActiveRecord::Base.establish_connection(
11+
adapter: "sqlite3",
12+
database: ":memory:"
13+
)
14+
ActiveRecord::Schema.define do
15+
self.verbose = false
16+
17+
create_table :test_records, force: true do |t|
18+
t.string :name
19+
t.belongs_to :person
20+
t.belongs_to :book
21+
t.timestamps
22+
end
23+
end
24+
25+
ActiveRecord::Base.extend(ActiveResource::Associations::ActiveRecord)
26+
27+
class TestRecord < ActiveRecord::Base
28+
belongs_to_resource :person
29+
belongs_to_resource :book, class_name: "Product"
30+
end
31+
end
32+
33+
def test_belongs_to_resource
34+
record = TestRecord.create(name: "test", person_id: 1)
35+
assert_equal record.person.name, "Matz"
36+
end
37+
38+
def test_belongs_to_resource_with_class_name
39+
record = TestRecord.create(name: "test", person_id: 1, book_id: 1)
40+
assert_equal record.book.name, "Rails book"
41+
end
42+
end

0 commit comments

Comments
 (0)