Skip to content

Commit c57ce29

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

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-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+
extend ActiveResource::Associations::ActiveRecord
28+
end
29+
end
2430
end
2531
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
ActiveRecord::Base.establish_connection(
10+
adapter: "sqlite3",
11+
database: ":memory:"
12+
)
13+
ActiveRecord::Schema.define do
14+
self.verbose = false
15+
16+
create_table :test_records, force: true do |t|
17+
t.string :name
18+
t.belongs_to :person
19+
t.belongs_to :book
20+
t.timestamps
21+
end
22+
end
23+
end
24+
25+
class TestRecord < ActiveRecord::Base
26+
include ActiveResource::Associations::ActiveRecord
27+
belongs_to_resource :person
28+
belongs_to_resource :book, class_name: "Product"
29+
end
30+
31+
def test_belongs_to_resource
32+
record = TestRecord.create(name: "test", person_id: 1)
33+
assert_equal record.person.name, "Matz"
34+
end
35+
36+
def test_belongs_to_resource_with_class_name
37+
record = TestRecord.create(name: "test", person_id: 1, book_id: 1)
38+
assert_equal record.book.name, "Rails book"
39+
end
40+
end

0 commit comments

Comments
 (0)