-
-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Associations with default attributes #18
Conversation
attributes = @attributes.merge(attributes) | ||
attributes.transform_values! do |value| | ||
if !value.respond_to?(:call) then value else | ||
klass ||= Struct.new(:id, *attributes.keys).new(id, *attributes.values) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Probably some of the most bananas code we've got now. It works! And we can always find something more performant later.
@attributes = {} | ||
end | ||
|
||
def with(**attributes) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Overall pretty happy with how relatively simple it turned out to implement default attributes. It's been on my wishlist since day one! And something that Fixtures aren't that suited for.
users.update :kasper, name: "Kasper" | ||
accounts.update :business, name: "Big Business Co." | ||
|
||
users.with name: -> { id.to_s.capitalize }, accounts: [accounts.business] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
accounts: [accounts.business]
here lets us ensure that every user created after here are automatically added to this account. And it's a through association through a Membership
class! And we don't have to write the separate Fixture file for those. That's a huge fixture pain gone right there.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Honestly, I'm still kinda stunned that it just worked. But we're just leaning on Active Record's user.accounts =
writer method from the has_many :accounts, through: :memberships
association.
Now we've got this: