Last active
February 16, 2017 21:31
-
-
Save psylone/e534cf238ebe97f7513a811385e820df to your computer and use it in GitHub Desktop.
Ruby association example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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