Skip to content

Commit

Permalink
Add support for namespaced models (#13)
Browse files Browse the repository at this point in the history
We got it, we just need to `demodulize` the `record` alias.
  • Loading branch information
kaspth authored Nov 5, 2023
1 parent 2ebd9c6 commit 45425bb
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,31 @@ class Post::Publisher < ActiveRecord::AssociatedObject
end
```

### Namespaced models

If you have a namespaced Active Record like this:

```ruby
# app/models/post/comment.rb
class Post::Comment < ApplicationRecord
belongs_to :post

has_object :rating
end
```

You can define the associated object in the same way it was done for `Post::Publisher` above, within the `Post::Comment` namespace:

```ruby
# app/models/post/comment/rating.rb
class Post::Comment::Rating < ActiveRecord::AssociatedObject
def great?
# A `comment` method is generated to access the associated comment. There's also a `record` alias available.
comment.author.subscriber_of? comment.post.author
end
end
```

### Remove Active Job boilerplate with `performs`

If you also bundle [`active_job-performs`](https://github.com/kaspth/active_job-performs) in your Gemfile like this:
Expand Down
2 changes: 1 addition & 1 deletion lib/active_record/associated_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class ActiveRecord::AssociatedObject
class << self
def inherited(klass)
record_klass = klass.module_parent
record_name = klass.module_parent_name.underscore
record_name = klass.module_parent_name.demodulize.underscore
attribute_name = klass.to_s.demodulize.underscore.to_sym

unless record_klass.respond_to?(:descends_from_active_record?) && record_klass.descends_from_active_record?
Expand Down
3 changes: 3 additions & 0 deletions test/active_record/associated_object_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ def setup
def test_associated_object_alias
assert_equal @post, @publisher.post
assert_equal @publisher.post, @publisher.record

assert_equal @comment, @rating.comment
assert_equal @rating.comment, @rating.record
end

def test_associated_object_method_missing_extraction
Expand Down
3 changes: 1 addition & 2 deletions test/boot/associated_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ class Post::Comment::Rating < ActiveRecord::AssociatedObject
kredis_flag :moderated

def great?
# TODO: Fix namespaced records generating a :"post/comments" alias instead of `post_comment` or `comment`
record.body == "First!!!!"
comment.body == "First!!!!"
end
end

0 comments on commit 45425bb

Please sign in to comment.