Skip to content

Instantly share code, notes, and snippets.

@psylone
Last active February 16, 2017 21:31
Show Gist options
  • Save psylone/e534cf238ebe97f7513a811385e820df to your computer and use it in GitHub Desktop.
Save psylone/e534cf238ebe97f7513a811385e820df to your computer and use it in GitHub Desktop.
Ruby association example
require 'faker'
module BelongsToAssociation
def self.included(receiver)
receiver.extend ClassMethods
end
module ClassMethods
def belongs_to(attribute)
class_eval do
define_method("#{attribute}=") do |value|
instance_variable_set("@#{attribute}", value)
association_name = self.class.to_s.downcase + 's'
send(attribute).send(association_name).push(self)
end
end
end
end
end
class User
attr_reader :posts
# has_many :posts
def initialize
@posts = []
end
end
class Post
attr_reader :user
include BelongsToAssociation
belongs_to :user
# belongs_to :comment
# belongs_to :image
def initialize(user:)
@title = Faker::Name.title
self.user = user
end
def to_s
"Post##{self.object_id}: #{@title}"
end
end
user = User.new
5.times { Post.new(user: user) }
user.posts.pop
puts user.posts
require 'faker'
class User
attr_reader :posts
def initialize
@posts = []
end
end
class Post
attr_reader :user
def initialize(user:)
@title = Faker::Name.title
self.user = user
end
def user=(user)
@user = user
user.posts.push(self)
end
def to_s
"Post##{self.object_id}: #{@title}"
end
end
user = User.new
5.times { Post.new(user: user) }
user.posts.pop
puts user.posts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment